Register Login

How to Print an Array in Java?

Java arrays allow programmers to keep data of similar types. This homogenous data structure stores data in a contiguous memory location. Printing the array elements gives us the visibility of the values we have inside the Java array. But we cannot print array elements directly in Java.

In this article, you will get to know the different methods of printing data from an array in Java.

What Happens if we Try to Print the Array Directly in Java?

public class Main{
public static void main(String[] args){
 	String arryData[] = { "Karlos", "Ray", "Dee" };
 	System.out.println(arryData);
	}
}

OUTPUT:

[Ljava.lang.String;@2a139a55

This program will show the output something like this which doesn’t seem meaningful. But no worries, as you do not have to look far as the Collection framework renders lots of array utilities within java.util.Arrays class.

Different Methods of Printing Java Arrays

1) Using the toString()

Arrays.toString() is Java's static method that comes as a part of the Arrays class belonging to java.util package. It is extremely simple to implement for printing out formatted versions of Java objects. Every class has a toString() method because all the class gets inherited from java.lang.Object (that is at the root of Java class hierarchy). To use toString() method for printing array elements, we have to import the java.util.Arrays. The toString() method is used when you want to print a single-dimensional array in Java.

Example:

import java.util.Arrays; 
public class Main{
	public static void main (String[] args){
		int[] sequenceArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};            				System.out.println(Arrays.toString(sequenceArr));
	}
}

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Code Explanation: 

Here we have to import java.util.Arrays for using the toString() method. We have created the array named sequenceArr of type integer and initialized it. To print the array elements, we have used System.out.println() and passed the array within Arrays.toString() method. The toString() takes a one-dimensional array as a parameter.

2. Using Arrays.deepToString():

Arrays.deepToString() is another method that comes as a part of the Arrays class. To use deepToString() method, we have to import the java.util.Arrays. Java provides this method so that programmers can print two or more dimensional arrays in Java. This method accepts an array as its parameter and returns the string representation of that array.

Example:

import java.util.Arrays;  
public class Main{
	public static void main (String[] args) {
		float[][] arry = {{1.1f, 2.2f, 3.3f}, {2.1f, 2.2f, 2.3f}, {3.6f, 4.6f, 5.6f}};  
            		System.out.println(Arrays.deepToString(arry));  
	}
}

Output:

[[1.1, 2.2, 3.3], [2.1, 2.2, 2.3], [3.6, 4.6, 5.6]]

Code Explanation: 

Here we have to import java.util.Arrays for using the deepToString() method. We have created a two-dimensional array named ‘arry’ of type float and initialized it. To print the array elements, we have used System.out.println() and passed the array within Arrays.deepToString() method. It takes a multidimensional array as parameter.

3. Using For Loop

For loop is one of the most popular looping constructs in Java. Using the for loop, a programmer can access each element of the array and fetch it to the output console for displaying it. It is the most commonly used method for displaying array elements.

Example:

import java.util.Arrays;  
public class Main{
	public static void main (String[] args) {
		int arry[] = new int[7];     
//initializing elements   
        arry[0]= 60;  
        arry[1] = 50;    
        arry[2]= 40;    
        arry[3] =30;
        arry[4] = 20;
        arry[5] =10;
        arry[6]= 0;
        // traversing each element of the array via for loop  
        for(int count=0; count<arry.length; count++)    //array’s length property is used
        	System.out.println(arry[count]);    
	}
}

Output:

60                                                                                                                                                       
50                                                                                                                                                       
40                                                                                                                                                       
30                                                                                                                                                       
20                                                                                                                                                       
10                                                                                                                                                       
0

Code Explanation: 

Here we have to import java.util.Arrays and created a class Main. We have created a one-dimensional array named ‘arry’ of type integer and initialized it one by one. To print the array elements one by one, we have used System.out.println() inside the for loop, which will traverse each element of the array one by one. The arry[count] will take each element and will display it using System.out.println().

4. Using Foreach Loop:

The foreach loop is another popular loop that programmers use popularly to traverse over an array or collection. It works based on the elements residing within the Java collection and returns each element one after another. We write it like this.

for(Type var:array)

Example:

import java.util.Arrays;  
public class Main{
	public static void main (String[] args){
	int arry[] = new int[7];     
//initializing elements   
        arry[0]=60;  
        arry[1]=50;    
        arry[2]=40;    
        arry[3] =30;
        arry[4]=20;
        arry[5]=10;
        arry[6]=0;
        // traversing each element of the array via for loop  
        for (Integer count : arry){  
                System.out.println(count);  
	        }
}
}

Output:

60                                                                                                                                                       
50                                                                                                                                                       
40                                                                                                                                                       
30                                                                                                                                                       
20                                                                                                                                                       
10                                                                                                                                                       
0

Code Explanation: 

Here we have to import java.util.Arrays and created a class Main. We have created a one-dimensional array named ‘arry’ of type integer and initialized it one by one. To print the array elements one by one, we have used System.out.println() inside the foreach loop. The count variable takes each element of the array one by one and directly displays it using System.out.println().

5. Using Arrays.asList() Method

Another static method of Java belonging to the Array class of java.util package is the Arrays.asList() method. This method creates a simple way of creating a fixed-size list that programmers can initialize for holding many elements.

Example

import java.util.Arrays; 
public class Main{
	public static void main (String[] args){
		String arryData[] = { "Karlos", "Ray", "Dee" };
 			  System.out.println(Arrays.asList(arryData));  
	}
}

Output:

[Karlos, Ray, Dee]

Code Explanation:

Here we have to import java.util.Arrays and created a class Main. Next, we have created a one-dimensional array named ‘arryData’ of type String and initialized 3 values within it. To print the array elements one by one, we have used System.out.println() and passed the Array.asList() method within it. The asList() method accepts the array (arryData) as an argument and returns the list view as the output of the array.

6. Using Java Iterator:

Like that of a foreach loop, we can use the Iterator of Java. Programmers use the Iterator interface for looping through all the elements which we can print. We can apply the iterator mechanism by invoking the iterator() method on a Collection. The iterator object is responsible for traversing each element of the collection. This method returns an iterator object.

Example:

import java.util.*; 
import java.util.Iterator;
public class Main{
	public static void main (String[] args){
 	Integer[] intArray = {20, 40, 60, 80, 100};
 	Double[] arr = { 1.5, 2.6, 3.7, 4.8, 5.9};
         	List<Integer> list2 = Arrays.asList(intArray);
        Iterator<Integer> itrr = list2.iterator();
        while(itrr.hasNext()){
            System.out.println(itrr.next());
            }              
        Iterator<Double> itrtr = Arrays.asList(arr).iterator();  
        while(itrtr.hasNext()){
            System.out.println(itrtr.next()); 
            }
}
}

Output:

20                                                                                                                                                         
40                                                                                                                                                         
60                                                                                                                                                         
80                                                                                                                                                         
100                                                                                                                                                        
1.5                                                                                                                                                        
2.6                                                                                                                                                        
3.7                                                                                                                                                        
4.8                                                                                                                                                        
5.9

Code Explanation:

Here we have to import java.util.* (here asterisk i.e., * means all other classes residing within the utility package) and created a class Main. Next, we have created two one-dimensional arrays named ‘intArray’ and ‘arr’ of type integer and double respectively and initialized them with values. Then we have created a List object and an iterator object to make the array a list and iterate over each element of it.

To print the array elements one by one, we have used System.out.println() within the while(itrr.hasNext()) loop. The hasNext() method of the Iterator will check whether there is any element to iterate or not. The next() method of the Iterator class finds and returns the next complete token from the scanner.

Using the Stream API of Java

The Stream API of Java is another popular means through which we can print Java arrays. This data structure gets executed on-demand. It works on the source data structure (like arrays and collections). It uses the concept of internal iteration and affords various features like parallel and sequential execution.

The stream method is a static Java method java.util package. It uses a sequential stream of an array. Now, using the foreach() terminal operation, programmers can iterate every stream element.

Here is a code snippet of how to use stream and foreach in a single statement:

import java.util.*;
import java.util.Iterator;
public class Main{
	public static void main (String[] args){
 	Integer[] arry = {20, 40, 60, 80, 100};
    Arrays.stream(arry).forEach(System.out :: print);
    System.out.print("\n Done");  	// This statement is just to show that the iteration in the 
                                    // previous line won’t have any affect on this
	}
}

Output:

20406080100                                                                                       
Done

Code Explanation:

Here we have to import java.util.* and created a class Main. Next, we have created a one-dimensional array object named ‘arry’ of type Integer and initialized them with values. Then we have directly used the Arrays object with the stream() method to sequentially stream the array values. We have used the period operator followed by a foreach to iterate every element of the stream.

Now inside the forEach() we have used the method called println() in conjunction with the standard output stream. Putting the println() method after member access operator (::) makes it an expression. The entire stream statement will iterate within itself unless it traverses all the elements of the array. You can understand this because the System.out.print("\n Done"); won't get executed in between.

Comparison Between All Methods


toString()

deepToString()

For Loop

Foreach Loop

asList()

Java Iterator

Stream API

O(1)

O(1)

O(n)

O(n)

O(1)

O(n)

O(n)

It is the most widely used method to display 1D arrays

It is the most widely used method to display 2D arrays

It is another widely used method to display arrays in an iterative fashion, but it is costly

It is widely used to traverse array elements in a sequence, but it is also costly

Here the array is converted into a List object which makes the entire process efficient

In this method, we need List object and Iterator object along with a loop which makes it the costliest of all methods

This is another costly method that uses foreach loop within itself and makes filter and map objects work faster with lesser lines of code

Conclusion

All these methods will print the output of array elements one by one. But some of these are worth using. The toString() method is the most efficient. The for loop and foreach loop are the most commonly used techniques to display array elements, but they are computationally less efficient as the time complexity becomes O(n). Iterators and Stream APIs are easy to use, but they are computationally slow because they get converted to List and stream objects first before performing the iteration on array elements.