Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to print a Java array?

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] 
like image 373
Alex Spurling Avatar asked Jan 03 '09 20:01

Alex Spurling


People also ask

How many ways can you print an array in Java?

Arrays in java are used to hold similar data types values.

How do you write a short array in Java?

Let us first declare and initialize an unsorted Short array. short[] arr = new short[] { 35, 25, 18, 45, 77, 21, 3 }; Now, let us short the array.


2 Answers

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

Examples:

  • Simple 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"}}; 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]] 
  • 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 ] 
like image 151
15 revs, 14 users 19% Avatar answered Oct 01 '22 13:10

15 revs, 14 users 19%


Always check the standard libraries first.

import java.util.Arrays; 

Then try:

System.out.println(Arrays.toString(array)); 

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array)); 
like image 34
Limbic System Avatar answered Oct 01 '22 15:10

Limbic System