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]
4 upvote
  flag
What do you want the representation to be for objects other than strings? The result of calling toString? In quotes or not? – Jon Skeet
2 upvote
  flag
Yes objects would be represented by their toString() method and without quotes (just edited the example output). – Alex Spurling
1 upvote
  flag
In practice, closely related to //allinonescript.com/questions/29140402/… – Raedwald
1 upvote
  flag
That weird output is not necessarily the memory location. It's the hashCode() in hexadecimal. See Object#toString(). – 4castle
1 upvote
  flag
To print single dimensional or multi-dimensional array in java8 check //allinonescript.com/questions/409784/… – i_am_zero
upvote
  flag

25 Answers 11

up vote 1840 down vote accepted

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 ]
upvote
  flag
This works for multi dimensional arrays too. – Alok Mishra
1 upvote
  flag
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? – Hengameh
2 upvote
  flag
@Hengameh: There are several other ways to do this, but my favorite is this one: javahotchocolate.com/notes/java.html#arrays-tostring . – Russ Bateman
2 upvote
  flag
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. – Marcus
upvote
  flag
@Hengameh There's a method dedicated to that. System.out.println(String.join(" ", new String[]{"John", "Mahta", "Sara"})) will print John Mahta Sara. – dorukayhan
3 upvote
  flag
Don't forget to import the Arrays library with import java.util.Arrays; – Steven Vascellaro
upvote
  flag
@Steven, see edit #10 - there's no need to specifically mention imports in every single post. As side note, as original creator of this answer it's incredible how much more complex this answer has gotten over the years. – Esko

Always check the standard libraries first. Try:

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

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));
upvote
  flag
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? – Hengameh
1 upvote
  flag
@Hengameh Just store Arrays.toString(array) to a string variable and then remove the braces by replace method of Java – Naveed Ahmad
4 upvote
  flag
@Hengameh Nowadays with Java 8: String.join(" ", Arrays.asList(array)). doc – Justin

If you're using Java 1.4, you can instead do:

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

(This works in 1.5+ too, of course.)

30 upvote
  flag
Unfortunately this only works with arrays of objects, not arrays of primitives. – Alex Spurling

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 ) );
upvote
  flag
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? – Hengameh
2 upvote
  flag
@Hengameh I think that's another topic. You can manipulate this String with the common string operations afterwards... Like Arrays.toString(myarray).replace("[", "("); and so on. – OddDev
for(int n: someArray) {
    System.out.println(n+" ");
}
5 upvote
  flag
This way you end up with an empty space ;) – Matthias
1 upvote
  flag
@ matthiad .. this line will avoid ending up with empty space System.out.println(n+ (someArray.length == n) ? "" : " "); – Muhammad Suleman
2 upvote
  flag
Worst way of doing it. – NamingException

Arrays.deepToString(arr) only prints on one line.

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr) method should take a separator string, but unfortunately it doesn't.

2 upvote
  flag
Maybe use System.getProperty("line.separator"); instead of \r\n so it is right for non-Windows as well. – Scooter
upvote
  flag
you can use System.lineSeparator() now – Novaterata

Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

3 upvote
  flag
It prints "1, 2, 3, 4, 5, " as output, it prints comma after the last element too. – icza
upvote
  flag
What's the solution for not having a comma after the last element? – Mona Jalal
2 upvote
  flag
You could replace the code within the loop with System.out.print(intArray[i]); if(i != intArray.length - 1) System.out.print(", "); – Nepoxx
1 upvote
  flag
You could also use System.out.print(i + (i < intArray.length - 1 ? ", " : "")); to combine those two lines. – Nick Suwyn
upvote
  flag
You could use a StringBuilder and truncate the trailing comma. int[] intArray = new int[] {1, 2, 3, 4, 5}; final StringBuilder sb = new StringBuilder(); for (int i : intArray) { sb.append(intArray[i]).append(", "); } if (sb.length() > 0) { sb.setLength(sb.length()-1); } System.out.println(sb.toString()); This outputs "1, 2, 3, 4, 5". – Rick Ryker

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
*/
38 upvote
  flag
Or less cumbersome, Arrays.stream(strArray).forEach(System.out::println); – Alexis C.
6 upvote
  flag
This is clumsy. It should be System.out::println which is a Java 8 method reference. You code produces an unnecessary lambda. – Boris the Spider
upvote
  flag
Just skip the Arrays.asList and do Arrays.stream(strArray).forEach(System.out::println) – Justin
upvote
  flag
@AlexisC. Even better, Stream.of – Yassin Hajaj
upvote
  flag
@YassinHajaj Why better? – Alexis C.
1 upvote
  flag
@AlexisC. Because it can also be used with other objects than arrays. – Yassin Hajaj
upvote
  flag
@YassinHajaj Yes, but the question specifically ask for an array. If you have an array, it's better to use Arrays.stream than Stream.of. – Alexis C.
upvote
  flag
@AlexisC. Is it better in terms of performance or just within the scope of this question? – Yassin Hajaj
1 upvote
  flag
@YassinHajaj Both. For instance if you want to have a range stream over the array the idiomatic way using Stream.of would be to do .skip(n).limit(m). The current implementation does not return a SIZED stream whereas Arrays.stream(T[], int, int) does, leading to better splitting performances if you want to perform operations in parallel. Also if you have an int[], you may accidentally use Stream.of which will return a Stream<int[]> with a single element, while Arrays.stream will give you an IntStream directly. – Alexis C.

To add to all the answers, printing the object as a JSON string is also an option.

Using Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

There's one additional way if your array is of type char[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

abc
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }

A simplified shortcut I've tried is this:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

It will print

1
2
3

No loops required in this approach and it is best for small arrays only

Prior to Java 8 we could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays. We have got the option of Stream and lambda in Java 8 which can also be used for the printing the array.

Printing One dimensional Array:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

Printing Multi-dimensional Array Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

The output is:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

upvote
  flag
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? – Hengameh

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

The simplest way to print an array is to use a for-loop:

// initialize array
for(int i=0;i<array.length;i++)
{
    System.out.print(array[i] + " ");
}
4 upvote
  flag
From 1 to 10? Seriously? – james.garriss
upvote
  flag
The correct for loop, assuming a T[] myArray, is for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i] + " "); } – Nic Hartley

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!".

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

I came across this post in Vanilla #Java recently. It's not very convenient writing Arrays.toString(arr);, then importing java.util.Arrays; all the time.

Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.

Printing an array directly gives the internal representation and the hashCode. Now, all classes have Object as the parent-type. So, why not hack the Object.toString()? Without modification, the Object class looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This modded class may simply be added to the class path by adding the following to the command line: -Xbootclasspath/p:target/classes.

Now, with the availability of deepToString(..) since Java 5, the toString(..) can easily be changed to deepToString(..) to add support for arrays that contain other arrays.

I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a System.outor a PrintWriter for such eventualities.

2 upvote
  flag
you want to execute these if conditions on every object? – sidgate
upvote
  flag
+1 just for the idea, but based on previous comment, can we mod the array implementations directly rather than depending on the Object common parent? Can we work that idea further out? Not that I think that modifying default behavior of java.lang.* objects is something I would encourage ... – YoYo

It should always work whichever JDK version you use:

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

It will work if the Array contains Objects. If the Array contains primitive types, you can use wrapper classes instead storing the primitive directly as..

Example:

int[] a = new int[]{1,2,3,4,5};

Replace it with:

Integer[] a = new Integer[]{1,2,3,4,5};

Update :

Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.

So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format as

public void printArray(int [] a){
        //write printing code
} 
1 upvote
  flag
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. – Debosmit Ray

In java 8 it is easy. there are two keywords

  1. stream: Arrays.stream(intArray).forEach
  2. method reference: ::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));
upvote
  flag
This will print each element of the array on a separate line so it does not meet the requirements. – Alex Spurling
upvote
  flag
if u want to print all elements in the array in the same line, then just use print instead of println i.e. int[] intArray = new int[] {1, 2, 3, 4, 5}; Arrays.stream(intArray).forEach(System.out::print); antotherway without methodreference just use int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(Arrays.toString(intArray)); – suatCoskun

You could loop through the array, printing out each item, as you loop. For example:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

item 1
item 2
item 3

Different Ways to Print Arrays in Java:

  1. Simple Way

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

Output: [One, Two, Three, Four]

  1. Using toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Output: [One, Two, Three, Four]

  1. Printing Array of Arrays

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]

Resource: Access An Array

for each loop can also be used to print elements of array:

int array[]={1,2,3,4,5};
for (int i:array)
System.out.println(i);
upvote
  flag
That is wrong the correct is : System.out.println(a[i]); – firephil
upvote
  flag
@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. – hasham.98
upvote
  flag
your are right the loop will iterate correctly – firephil
upvote
  flag
Yes It works, but it is not the simplest way. – Hardy Feng

There Are Following way to print Array

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(Integer lists : arrayInt){
         System.out.println(lists);
     }

String[] array = { "a", "b", "c" };
System.out.println(Arrays.toString(array));

upvote
  flag
Usage of Arrays.toString is already included in the top-voted, accepted answer – ivarni

Not the answer you're looking for? Browse other questions tagged or ask your own question.