What’s the Simplest Way to Print a Java Array?
In Java, arrays don’t override the toString()
method. Therefore, printing an array directly results in the output of the class name followed by ‘@’ and the hexadecimal hash code of the array, as defined by Object.toString()
. For example:
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // Prints something like '[I@3343c8b3'
However, we usually want a more readable output like [1, 2, 3, 4, 5]
. What’s the simplest way to achieve that? Here are some example inputs and outputs:
-
Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5}; // Output: [1, 2, 3, 4, 5]
-
Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"}; // Output: [John, Mary, Bob]
Can anyone help ?