How to print array in Java23 Oct 2024 | 7 min read Java array is a data structure where we can store the elements of the same data type. The elements of an array are stored in a contiguous memory location. So, we can store a fixed set of elements in an array. There are following ways to print an array in Java:
Java for loopJava for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. Syntax: Example of for loop In the following example, we have created an array of length four and initialized elements into it. We have used for loop for fetching the values from the array. It is the most popular way to print array in Java. Filename: PrintArrayExample1.java Output: 10 20 70 40 Explanation The given Java code creates an integer array arr of size 4 and sets certain values for each of its components. The array is then iterated over using a for loop, and each element is printed using System.out.println() on a new line. This code skillfully demonstrates Java array declaration, instantiation, initialization, and traversal. Java while LoopThe while loop in Java is a control flow statement that allows a set of statements to be executed repeatedly as long as a specified condition evaluates to true. Filename: PrintArrayExample.java Output: 1 2 3 4 5 Java for-each loopJava for-each loop is also used to traverse over an array or collection. It works on the basis of elements. It returns elements one by one in the defined variable. Syntax: Example of for-each loop In the following example, we have created an array of String type of length four and initialized elements into it. We have used for-each loop to traverse over the array. Filename: PrintArrayExample2.java Output: Delhi Jaipur Gujarat Mumbai Explanation The supplied Java code creates a string array called city with a capacity of 4 and gives each entry a specific city name. It iterates through each element of the array and prints each one separately using a for-each loop. This code clearly illustrates how to use a for-each loop in Java to iterate over arrays, providing a clear and understandable method of accessing array components without the need for explicit index management. Java Arrays.toString() MethodJava Arrays.toString() is a static method of the Arrays class that belongs to Java.util package. It contains various methods for manipulating arrays. Syntax: It accepts an array of any primitive type as an argument. It returns a string representation of an array that contains a list of array's elements. The elements of an array are converted to String by String.valueOf(int) . Example of toString() MethodFilename: PrintArrayExample3.java Output: [34, -10, 56, -9, -33] Explanation The given Java code prints a string representation of the integer array array by using the Arrays.toString() method from the java.util.Arrays class. Using square brackets and commas to separate the elements, this method formats the array's elements into a string. Arrays.toString(array) is the argument passed to System.out.println(), which prints the array's string representation to the console. This method makes it easy to view an array's contents as a single string, which helps with output formatting and debugging in Java programmes. Java Arrays.deepToString() MethodThe deepToString() method of Java Arrays class is designed for converting multidimensional arrays to strings. Syntax: It accepts an array as a parameter. It returns the String representation of an array. Example of deepToString() Method In the following example, we have created a two dimensional array of float type. Filename: PrintArrayExample4.java Output: [[1.2, 2.5], [3.9, 4.0], [5.3, 6.2]] Explanation Using an array initializer, the provided Java code initializes a two-dimensional float array called an array. There are two float values in each of the three rows that make up this array. the java.util.Arrays.deepToString() function. Then, the array is used as the argument when invoking the Arrays class. By using square brackets to enclose each nested array's string representation and commas to separate the rows, this approach transforms the two-dimensional array into a string representation. Java Arrays.asList() MethodJava Arrays.asList() is a static method of the Java Arrays class that belongs to Java.util package. It acts as a bridge between array-based and collection-based APIs. Syntax: The method also provides an easy way to create a fixed-size list initialize to contain many elements. It accepts an array as an argument. It returns the list view of an array. Example of asList() method Filename: PrintArrayExample5.java Output: [Hello, Java, Programmers] Explanation "Hello," "Java," and "Programmers" are the three items initialized in a one-dimensional array of strings called stringArray by the Java code provided. The array is then transformed into a List using the Arrays.asList() function from the java.util.Arrays class. The function returns the elements of the array as the elements of a List. Java Iterator interfaceJava Iterator is an interface which belongs to java.util package. The Iterator object can be created by calling iterator() method. It is present in Collection interface. It returns an iterator. Example of Iterator interface In the following, example, we have declare an array and initialize elements into it. We first convert the specified array into list by using Arrays.asList() method because iterator allows us to traverse over the collection and then invoke iterator() method of collection class. Filename: PrintArrayExample6.java Output: 1.5 2.6 3.7 4.8 5.9 Explanation Five double values are used to initialize an array of double type called array in the Java code. It uses Arrays.asList() to turn this array into a List, and then it pulls an iterator out of this List. Using a while loop, it prints each element to the console as iterates through the List's elements using the iterator. This technique provides sequential access to array elements using an iterator, offering a conventional means of browsing collections. Java Stream APIA Java Stream is a computed-on-demand data structure. It does not store data. It operates on the source data structure, such as a collection or array. The Java stream API is used to implement internal iteration. It provides several features, such as sequential and parallel execution. Java stream() MethodJava stream() is a static method of Java Arrays class which belongs to java.util package. It is used to get a sequential stream of an array. Syntax: Where T is the type of array. The method accepts an array whose elements are to be converted into a sequential stream. It returns a sequential IntStream with the specified array as its source. Java forEach() methodIt is a terminal operation. It does not guarantee to respect the encounter order of the stream. Syntax: The method accepts an action as a parameter. It is non-interfering action perform on each element. It does not return anything. There are two terminal operations which we can apply to a stream to print an array. Get an iterator to the stream Using stream().forEach() Example of stream.forEach() Method In the following example, we have used a different way to print an array. The forEach() method is used to iterate over every element of the stream. It is defined in the Iterable and Stream interface. Inside the forEach() method we have used System.out which is a reference to an object. It represent standard output stream. It has a method called println(). It is an overloaded method which can accept anything as an argument. When we put println() method after member access operator (::), it becomes an expression. Filename: PrintArrayExample7.java Output: Java C C++ Python Perl Explanation The provided Java code initializes an array of strings called arr with five elements. The array is subsequently transformed into a stream using the Arrays.stream() method and Java 8's Stream API. The Stream is subjected to the forEach() terminal operation, which causes each element to be printed to the console by invoking System.out's println() method. This method iterates through the array and concisely prints its contents by utilizing functional programming ideas. Next TopicJava Tutorial |
In this section, we are going to learn about stars numbers in Java. The stars number resembles the board of the Chinese checkers game. A star number is a hexagram. Here, a hexagram means a six-pointed star. Observe the following diagram. Mathematically, the number is represented by Sn...
9 min read
An array arr[] is given to us that contains n integers. Our task is to sort the array in such a way that a wiggle sequence is formed. If multiple wiggle sequence is there, then print anyone of them. A wiggle sequence for an array satisfies...
6 min read
? In Java, removing a substring from a string involves manipulating the original string to exclude the specified substring. This process can be achieved by various means, typically involving string handling methods that identify the position of the substring and then create a new string without the...
10 min read
Java Runnable Interface Java runnable is an interface used to execute code on a concurrent thread. It is an interface which is implemented by any class if we want that the instances of that class should be executed by a thread. The runnable interface has an undefined method...
5 min read
The Rotate Bits problem involves shifting the bits of an integer to the left or right, wrapping the overflowed bits to the opposite end. This operation is crucial in low-level programming, cryptography, and data manipulation tasks. Java provides bitwise operators to implement this efficiently for both...
7 min read
? In this section, we will understand the logic to print tables and also implement that logic in Java programs. A table (or multiplication table) is a sequence of numbers that are generated using multiplication. We enter an integer as input of which we want to print the...
2 min read
The task of finding numbers whose units digit is equal to k and their sum is equal to the given num is an interesting computational problem which can be solved using different approaches in Java. Example 1 Input num = 58, k = 9 Output: 2...
7 min read
Kahn's algorithm is a popular method used to perform topological sorting on a directed acyclic graph (DAG). Topological sorting is ordering the vertices in a DAG, such that for every directed edge (u, v), vertex u comes before vertex v in the ordering. In other words,...
8 min read
Exception handling is an essential aspect of programming, enabling developers to gracefully manage and recover from unforeseen errors. In Java, exceptions are categorized as checked or unchecked, with checked exceptions requiring explicit handling in the code. This article focuses on checked exceptions in Java, providing a...
6 min read
In Java, a package is a group of classes, sub-packages, and interfaces. It supports organisation of existing classes into a folder structure, making them easier to find and utilise. More importantly, it promotes the reuse of code. Each package has its own name. The classes and...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India