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

ID : 377

viewed : 67

Tags : javaarraysprintingjava

Top 5 Answer for What's the simplest way to print a Java array?

vote vote

97

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 ] 
vote vote

81

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)); 
vote vote

71

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

import java.util.Arrays; . . . System.out.println( Arrays.toString( myarray ) ); 
vote vote

70

In JDK1.8 you can use aggregate operations and a lambda expression:

String[] strArray = new String[] {"John", "Mary", "Bob"};  // #1 Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));  // #2 Stream.of(strArray).forEach(System.out::println);  // #3 Arrays.stream(strArray).forEach(System.out::println);  /* output: John Mary Bob */ 
vote vote

58

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"}; String delimiter = " "; String.join(delimiter, greeting)  

The output will be "Hey there amigo!".

Top 3 video Explaining What's the simplest way to print a Java array?

Related QUESTION?