In Java, arrays don't override toString()
, so if you try to print one directly, you get the className
+ '@' + the hex of the hashCode
of the array, as defined by Object.toString()
:
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // prints something like '[I@3343c8b3'
But usually, we'd actually want something more like [1, 2, 3, 4, 5]
. What's the simplest way of doing 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]
Best Solution
Since Java 5 you can use
Arrays.toString(arr)
orArrays.deepToString(arr)
for arrays within arrays. Note that theObject[]
version calls.toString()
on each object in the array. The output is even decorated in the exact way you're asking.Examples:
Simple Array:
Output:
Nested Array:
Output:
double
Array:Output:
int
Array:Output: