What's the simplest way to print a Java array?
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);
Alex Spurling
Updated on March 15, 2022Comments
-
Alex Spurling over 2 years
In Java, arrays don't override
toString()
, so if you try to print one directly, you get theclassName
+ '@' + the hex of thehashCode
of the array, as defined byObject.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]
-
Jon Skeet over 15 yearsWhat do you want the representation to be for objects other than strings? The result of calling toString? In quotes or not?
-
Alex Spurling over 15 yearsYes objects would be represented by their toString() method and without quotes (just edited the example output).
-
Raedwald over 8 yearsIn practice, closely related to stackoverflow.com/questions/29140402/…
-
4castle over 7 yearsThat weird output is not necessarily the memory location. It's the
hashCode()
in hexadecimal. SeeObject#toString()
. -
akhil_mittal over 7 yearsTo print single dimensional or multi-dimensional array in java8 check stackoverflow.com/questions/409784/…
-
Stevoisiak almost 7 years
-
John McClane about 4 years
-
-
Alex Spurling over 15 yearsUnfortunately this only works with arrays of objects, not arrays of primitives.
-
Scooter over 10 yearsMaybe use System.getProperty("line.separator"); instead of \r\n so it is right for non-Windows as well.
-
icza over 10 yearsIt prints "1, 2, 3, 4, 5, " as output, it prints comma after the last element too.
-
Nepoxx almost 10 yearsYou could replace the code within the loop with
System.out.print(intArray[i]); if(i != intArray.length - 1) System.out.print(", ");
-
Matthias almost 10 yearsThis way you end up with an empty space ;)
-
Muhammad Suleman about 9 years@ matthiad .. this line will avoid ending up with empty space System.out.println(n+ (someArray.length == n) ? "" : " ");
-
Hengameh almost 9 yearsWhat 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 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 over 8 yearsFYI,
Arrays.deepToString()
accepts only anObject []
(or an array of classes that extendObject
, such asInteger
, so it won't work on a primitive array of typeint []
. ButArrays.toString(<int array>)
works fine for primitive arrays. -
Nick Suwyn over 8 yearsYou could also use
System.out.print(i + (i < intArray.length - 1 ? ", " : ""));
to combine those two lines. -
Justin over 8 years@Hengameh Nowadays with Java 8:
String.join(" ", Arrays.asList(array))
. doc -
Debosmit Ray about 8 yearsConverting 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 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 over 7 years@Hengameh There's a method dedicated to that.
System.out.println(String.join(" ", new String[]{"John", "Mahta", "Sara"}))
will printJohn Mahta Sara
. -
Manjitha Teshara almost 6 yearsint array[] = {1, 2, 3, 4, 5}; for (int i:array) System.out.println(i);
-
Manjitha Teshara almost 6 yearstry this i think this is shortest way to print array
-
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 wheni
is equal to the array length. -
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 over 5 yearsThis 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 finalSystem.out.println()
and used it injoiner.add(element.toString())
instead of adding the empty string. This solution works for arrays of non-primitive types as well, uniformly. -
John McClane over 5 yearsMy bad,
element.toString()
insidejoiner.add()
is for non-primitive types only. You still need to useInteger.toString(element)
- like constructs for primitive types. Personally, I used foreach loopfor (int element : array) joiner.add(Integer.toString(element));
instead of streams, but that's the matter of taste. -
CryptoFool over 5 yearsThis 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 over 4 yearsDon't forget "import java.util.Arrays;"
-
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 about 4 yearsAdding a dependency because of something trivial that be done in two lines of code is a screaming antipattern.
-
Haim Raman about 4 yearscommons-lang3 is a very poplar dependency, and note that this answer was were most people didn't used java 8
-
Mehdi almost 4 yearsThose 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 almost 4 yearsIf you don't import, you can write
java.util.Arrays.toString(array)
-
Marc H. over 3 yearsStill 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 over 3 yearsAlso, don't forget to override
Object#toString()
if the array contains an object type other thanString
or a primitive wrapper class. -
Prashant about 2 yearsif you use IntStream.of(ints).forEach(System.out::print); i don't think it will print in new line..