How to Print an Array in Java

Learn to print simple arrays as well as 2d arrays in Java. For multi-dimensional arrays or nested arrays, the arrays inside the array will also be traversed to print the elements stored in them.

1. Print a Simple Array

1.1. Using Arrays.toString()

The recommended way to print the content of an array is using Arrays.toString().

String[] array = new String[] { "First", "Second", "Third", "Fourth" };

System.out.println( Arrays.toString(array) );  //[First, Second, Third, Fourth]

1.2. Using Iteration

Another way to print a simple array is by using iteration. We can iterate the array elements and print them to the console one by one. We can iterate an array in many ways such as simple for loop, foreach loop, Stream API etc.

//Simple for-loop
for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

//Enhanced for-loop
for (String element : array) {
    System.out.println(value);
}

//Iterate Stream Elements
Arrays.stream(array).forEach(System.out::println);

2. Print Nested Arrays

2.1. Using Arrays.deepToString()

What will happen if, somewhere in the hierarchy, another array is stored, like in the case of an array of arrays? Use Arrays.deepToString() to print arrays containing other arrays, i.e, 2D arrays.

String[] arr1 = new String[] { "Fifth", "Sixth" };
String[] arr2 = new String[] { "Seventh", "Eight" };
String[][] arrayOfArray = new String[][] { arr1, arr2 };	

// Print the nested array
System.out.println(Arrays.deepToString(arrayOfArray));	   //[[Fifth, Sixth], [Seventh, Eighth]]

2.2. Using ArrayUtils.toString()

Another useful method is Apache Common Lang‘s ArrayUtils.toString(). It provides excellent support to print multi-dimensional primitive and non-primitive arrays.

System.out.println( ArrayUtils.toString(arrayOfArray) );

3. Conclusion

This short Java tutorial taught us how to print an array in Java with and without loops. We learned to print a simple array using Arrays.toString() and print multidimensional arrays using Arrays.deepToString(). Note that it does not make any difference if the array elements are primitives or object types. The solution to print the array elements remain the same.

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode