Printing Java Arrays to the Console
When working with arrays in Java, you often need to print their contents for debugging or output purposes. However, directly printing an array using System.out.println()
doesn’t produce the readable format you might expect. Instead, it prints something like [I@3343c8b3
, which represents the array’s class name and its hash code. This isn’t very useful for understanding the array’s actual values.
This tutorial demonstrates how to print Java arrays in a user-friendly format, displaying the array elements within square brackets separated by commas.
The Arrays.toString()
Method
The simplest and most effective way to print a Java array is to use the Arrays.toString()
method from the java.util.Arrays
class. This method is available starting from Java 5. It’s designed specifically for this purpose and produces the desired output format.
import java.util.Arrays;
public class PrintArray {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(intArray)); // Output: [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(strArray)); // Output: [John, Mary, Bob]
}
}
Handling Multi-Dimensional Arrays
For multi-dimensional arrays (arrays of arrays), Arrays.toString()
provides a basic representation, but it might not be exactly what you want. For deeply nested arrays, you can use Arrays.deepToString()
to achieve a more readable, recursive printing of all elements.
import java.util.Arrays;
public class PrintDeepArray {
public static void main(String[] args) {
String[][] deepArray = {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray)); // Output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray)); // Output: [[John, Mary], [Alice, Bob]]
}
}
Notice that Arrays.toString()
on a nested array prints the string representation of the inner arrays themselves, while Arrays.deepToString()
recursively prints the elements within the nested arrays.
Alternative Approaches (Java 8 and later)
While Arrays.toString()
is often the most convenient approach, Java 8 introduced the Stream API, which provides alternative ways to achieve the same result.
import java.util.Arrays;
import java.util.stream.Stream;
public class PrintArrayStream {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"John", "Mary", "Bob"};
// Using IntStream for int arrays
IntStream.of(intArray).forEach(System.out::println);
// Using Stream for String arrays
Stream.of(strArray).forEach(System.out::println);
}
}
This approach is less concise than using Arrays.toString()
, and it prints each element on a separate line, rather than a comma-separated list within square brackets.