Successful Java, arrays don't override toString()
, truthful if you attempt to mark 1 straight, you acquire the className
+ '@' + the hex of the hashCode
of the array, arsenic outlined by Object.toString()
:
int[] intArray = new int[] {1, 2, 3, 4, 5};System.out.println(intArray); // Prints something like '[I@3343c8b3'
However normally, we'd really privation thing much similar [1, 2, 3, 4, 5]
. What's the easiest manner of doing that? Present are any illustration 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]
Since Java 5 you tin usage Arrays.toString(arr)
oregon Arrays.deepToString(arr)
for arrays inside arrays. Line that the Object[]
interpretation calls .toString()
connected all entity successful the array. The output is equal embellished successful the direct manner you're asking.
Examples:
Elemental Array:
String[] array = new String[] {"John", "Mary", "Bob"};System.out.println(Arrays.toString(array));
Output:
[John, Mary, Bob]
Nested Array:
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};// Gives undesired output:System.out.println(Arrays.toString(deepArray));// Gives the desired output:System.out.println(Arrays.deepToString(deepArray));
Output:
[[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922][[John, Mary], [Alice, Bob]]
double
Array:double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };System.out.println(Arrays.toString(doubleArray));
Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int
Array:int[] intArray = { 7, 9, 5, 1, 3 };System.out.println(Arrays.toString(intArray));
Output:
[7, 9, 5, 1, 3 ]
Ever cheque the modular libraries archetypal.
import java.util.Arrays;
Past attempt:
System.out.println(Arrays.toString(array));
oregon if your array comprises another arrays arsenic components:
System.out.println(Arrays.deepToString(array));
Mistake producing weblog contented
Print the star pattern using Java
Print the star pattern using Java from Youtube.com