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

2,866,216

Solution 1

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 ]
    

Solution 2

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

Solution 3

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

Solution 4

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
*/

Solution 5

Arrays.toString

As a direct answer, the solution provided by several, including @Esko, using the Arrays.toString and Arrays.deepToString methods, is simply the best.

Java 8 - Stream.collect(joining()), Stream.forEach

Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the Stream.collect operator, using a joining Collector, to mimic what the String.join is doing.

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);
Share:
2,866,216
Alex Spurling
Author by

Alex Spurling

Updated on March 15, 2022

Comments

  • Alex Spurling
    Alex Spurling over 2 years

    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]
    
  • Alex Spurling
    Alex Spurling over 15 years
    Unfortunately this only works with arrays of objects, not arrays of primitives.
  • Scooter
    Scooter over 10 years
    Maybe use System.getProperty("line.separator"); instead of \r\n so it is right for non-Windows as well.
  • icza
    icza over 10 years
    It prints "1, 2, 3, 4, 5, " as output, it prints comma after the last element too.
  • Nepoxx
    Nepoxx almost 10 years
    You could replace the code within the loop with System.out.print(intArray[i]); if(i != intArray.length - 1) System.out.print(", ");
  • Matthias
    Matthias almost 10 years
    This way you end up with an empty space ;)
  • Muhammad Suleman
    Muhammad Suleman about 9 years
    @ matthiad .. this line will avoid ending up with empty space System.out.println(n+ (someArray.length == n) ? "" : " ");
  • Hengameh
    Hengameh almost 9 years
    What if we have an array of strings, and want simple output; like: String[] array = {"John", "Mahta", "Sara"}, and we want this output without bracket and commas: John Mahta Sara?
  • Russ Bateman
    Russ Bateman almost 9 years
    @Hengameh: There are several other ways to do this, but my favorite is this one: javahotchocolate.com/notes/java.html#arrays-tostring .
  • Marcus
    Marcus over 8 years
    FYI, Arrays.deepToString() accepts only an Object [] (or an array of classes that extend Object, such as Integer, so it won't work on a primitive array of type int []. But Arrays.toString(<int array>) works fine for primitive arrays.
  • Nick Suwyn
    Nick Suwyn over 8 years
    You could also use System.out.print(i + (i < intArray.length - 1 ? ", " : "")); to combine those two lines.
  • Justin
    Justin over 8 years
    @Hengameh Nowadays with Java 8: String.join(" ", Arrays.asList(array)). doc
  • Debosmit Ray
    Debosmit Ray about 8 years
    Converting an Array to a List simply for printing purposes does not seem like a very resourceful decision; and given that the same class has a toString(..), it defeats me why someone would ever do this.
  • hasham.98
    hasham.98 over 7 years
    @firephil System.out.println(a[i]); is used with ordinary for loop, where index "i" is created and value at every index is printed. I have used "for each" loop. Give it a try, hope you will get my point.
  • dorukayhan
    dorukayhan over 7 years
    @Hengameh There's a method dedicated to that. System.out.println(String.join(" ", new String[]{"John", "Mahta", "Sara"})) will print John Mahta Sara.
  • Manjitha Teshara
    Manjitha Teshara almost 6 years
    int array[] = {1, 2, 3, 4, 5}; for (int i:array) System.out.println(i);
  • Manjitha Teshara
    Manjitha Teshara almost 6 years
    try this i think this is shortest way to print array
  • Radiodef
    Radiodef almost 6 years
    @MuhammadSuleman That doesn't work, because this is a for-each loop. n is the actual value from the array, not the index. For a regular for loop, it would also be (someArray.length - 1) == i, because it breaks when i is equal to the array length.
  • Amadán
    Amadán almost 6 years
    @dorukayhan Actually you can omit explicitly instantiating the array here: String.join(" ", "John", "Mahta", "Sara")for the .join(...) method takes the array as a vararg parameter.
  • John McClane
    John McClane over 5 years
    This is better than the accepted answer in that it gives more control over the delimiter, prefix and suffix. However, I would remove superfluous toString() in the final System.out.println() and used it in joiner.add(element.toString()) instead of adding the empty string. This solution works for arrays of non-primitive types as well, uniformly.
  • John McClane
    John McClane over 5 years
    My bad, element.toString() inside joiner.add() is for non-primitive types only. You still need to use Integer.toString(element) - like constructs for primitive types. Personally, I used foreach loop for (int element : array) joiner.add(Integer.toString(element)); instead of streams, but that's the matter of taste.
  • CryptoFool
    CryptoFool over 5 years
    This is what I do. With this, you can print arbitrarily complex structures as long as they're encodable to JSON. I always make sure to use "pretty". Does your second example do that? I'd think you'd need to tickle a "pretty" option to get that.
  • M.Hossein Rahimi
    M.Hossein Rahimi over 4 years
    Don't forget "import java.util.Arrays;"
  • GotoFinal
    GotoFinal over 4 years
    "the memory address whose array(number array) declared is printed" That's not true at all, its system hash code of object, and this can be based on many things, including memory address, but this could change later and hash code would not change. And currently its mostly a random number. gotofinal.dev/java/2017/10/08/java-default-hashcode.html
  • jurez
    jurez about 4 years
    Adding a dependency because of something trivial that be done in two lines of code is a screaming antipattern.
  • Haim Raman
    Haim Raman about 4 years
    commons-lang3 is a very poplar dependency, and note that this answer was were most people didn't used java 8
  • Mehdi
    Mehdi almost 4 years
    Those who created a vote to remove my answer .. can you expose your point of view so everyone can learn ? The question asked for the simplest way in java, so it's a one liner, java current version is >14 and my solution is for at least java 8 ( so it is applicable ).
  • Omkar76
    Omkar76 almost 4 years
    If you don't import, you can write java.util.Arrays.toString(array)
  • Marc H.
    Marc H. over 3 years
    Still the best solution as also referred in stackoverflow.com/questions/38425623/… commons-lang is of course really popular and should be used instead of implement yourself. Such utility methods have to be tested and should also be accessible for other projects. As long as primitive arrays can not simple handled, a library like common-lang with overloaded methods is for me the best and efficient way to solve this problem.
  • hfontanez
    hfontanez over 3 years
    Also, don't forget to override Object#toString() if the array contains an object type other than String or a primitive wrapper class.
  • Prashant
    Prashant about 2 years
    if you use IntStream.of(ints).forEach(System.out::print); i don't think it will print in new line..