By Alex Spurling

2009-01-03 20:39:39 8 Comments

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 '[[email protected]'

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]


@Chen Jin 2019-10-20 16:56:57

toString is a way to convert an array to string.

Also, you can use:

for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i] + " ");

This for loop will enable you to print each value of your array in order.

@Esko 2009-01-03 20:43:44

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.


  • Simple Array:

    String[] array = new String[] {"John", "Mary", "Bob"};


    [John, Mary, Bob]
  • Nested Array:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]


    [[John, Mary], [Alice, Bob]]
  • double Array:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };


    [7.0, 9.0, 5.0, 1.0, 3.0 ]
  • int Array:

    int[] intArray = { 7, 9, 5, 1, 3 };


    [7, 9, 5, 1, 3 ]

@Hengameh 2015-08-29 02:34:41

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 2015-08-29 06:16:05

@Hengameh: There are several other ways to do this, but my favorite is this one: .

@Marcus 2015-12-11 23:25:12

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.

@user8397947 2017-03-13 14:15:53

@Hengameh There's a method dedicated to that. System.out.println(String.join(" ", new String[]{"John", "Mahta", "Sara"})) will print John Mahta Sara.

@Amadán 2018-08-18 08:12:13

@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.

@wafflecat 2019-01-17 06:07:38

You sir, are a prince among men.

@gaurav 2019-05-03 19:21:51

flawless answer Sir!

@Hossein Rahimi 2019-10-21 21:48:53

Don't forget "import java.util.Arrays;"

@Pradip Karki 2019-01-01 23:34:11

If using Commons.Lang library, we could do:


int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};



@shellhub 2018-12-10 07:57:58

if you are running jdk 8.

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]"); -> joiner.add(element + ""));

int[] array = new int[]{7, 3, 5, 1, 3};



@John McClane 2018-12-14 14:42:08

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 2018-12-14 15:02:50

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.

@akhil_mittal 2015-06-19 06:10:28

Prior to Java 8

We could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays.

Java 8

Now we have got the option of Stream and lambda to print 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

    // In Java 8 we have lambda expressions;;

The output is:

[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

    // In Java 8 we have lambda expressions ->; ->;

Now the point to observe is that the method[]), 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]]

@Hengameh 2015-08-29 02:33:51

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?

@YoYo 2016-03-11 05:36:49


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(", ")));

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

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

// These options are not the same as each item is printed on a new line:

@Sudip Bhandari 2018-07-06 12:29:41

If you want to print, evaluate Array content like that you can use Arrays.toString

jshell> String[] names = {"ram","shyam"};
names ==> String[2] { "ram", "shyam" }

jshell> Arrays.toString(names);
$2 ==> "[ram, shyam]"


@GT_hash 2018-07-01 15:45:41

There are several ways to print an array elements.First of all, I'll explain that, what is an array?..Array is a simple data structure for storing data..When you define an array , Allocate set of ancillary memory blocks in RAM.Those memory blocks are taken one unit ..

Ok, I'll create an array like this,

class demo{
      public static void main(String a[]){

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


Now look at the output,

enter image description here

You can see an unknown string printed..As I mentioned before, the memory address whose array(number array) declared is printed.If you want to display elements in the array, you can use "for loop " , like this..

class demo{
      public static void main(String a[]){

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

           int i;

                 System.out.print(number[i]+"  ");

Now look at the output,

enter image description here

Ok,Successfully printed elements of one dimension array..Now I am going to consider two dimension array..I'll declare two dimension array as "number2" and print the elements using "Arrays.deepToString()" keyword.Before using that You will have to import 'java.util.Arrays' library.

 import java.util.Arrays;

 class demo{
      public static void main(String a[]){

           int[][] number2={{1,2},{3,4},{5,6}};`


consider the output,

enter image description here

At the same time , Using two for loops ,2D elements can be printed..Thank you !

@Manjitha teshara 2018-08-04 16:22:44

int array[] = {1, 2, 3, 4, 5}; for (int i:array) System.out.println(i);

@Manjitha teshara 2018-08-04 16:23:15

try this i think this is shortest way to print array

@GotoFinal 2020-01-14 12:14:05

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

@Peter Lawrey 2018-06-22 19:17:10

This is marked as a duplicate for printing a byte[]. Note: for a byte array there are additional methods which may be appropriate.

You can print it as a String if it contains ISO-8859-1 chars.

String s = new String(bytes, StandardChars.ISO_8559);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);

or if it contains a UTF-8 string

String s = new String(bytes, StandardChars.UTF_8);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);

or if you want print it as hexadecimal.

String s = DatatypeConverter.printHexBinary(bytes);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);

or if you want print it as base64.

String s = DatatypeConverter.printBase64Binary(bytes);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);

or if you want to print an array of signed byte values

String s = Arrays.toString(bytes);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = Byte.parseByte(split[i]);

or if you want to print an array of unsigned byte values

String s = Arrays.toString(
               IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.

@Mehdi 2018-04-20 18:25:43

In java 8 :;

@Ravi Patel 2017-09-25 13:29:39

There Are Following way to print Array

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

// 2 for loop()
    for (int number : arrayInt) {

// 3 for each()
    for(int x: arrayInt){

@fjnk 2018-03-16 01:17:33

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

@hasham.98 2016-12-05 20:10:38

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

int array[] = {1, 2, 3, 4, 5};
for (int i:array)

@hasham.98 2016-12-25 21:22:43

@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.

@Manjitha teshara 2018-08-04 16:20:25

Yes,this is the shortest way to print array

@Singh123 2017-12-20 08:52:11

You could use Arrays.toString()

String[] array = { "a", "b", "c" };  

@Joy Kimaru 2015-10-01 03:12:22

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] + " ");

@Fund Monica's Lawsuit 2016-01-17 00:27:57

The correct for loop, assuming a T[] myArray, is for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i] + " "); }

@Affy 2016-08-07 14:05:06

Different Ways to Print Arrays in Java:

  1. Simple Way

    List<String> list = new ArrayList<String>();
    // Print the list in console

Output: [One, Two, Three, Four]

  1. Using toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };

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

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

Resource: Access An Array

@suatCoskun 2016-06-26 15:30:48

In java 8 it is easy. there are two keywords

  1. stream:
  2. method reference: ::println

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

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

Another way without method reference just use:

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

@Alex Spurling 2016-06-29 15:51:11

This will print each element of the array on a separate line so it does not meet the requirements.

@suatCoskun 2016-06-29 20:56:46

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};; antotherway without methodreference just use int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(Arrays.toString(intArray));

@Dylan Black 2016-07-20 23:55:49

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++) {




item 1
item 2
item 3

@Greesh Kumar 2016-05-13 11:01:00

It should always work whichever JDK version you use:


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


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

@Debosmit Ray 2016-05-13 11:35:36

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.

@Eric Baker 2014-02-06 23:35:32

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

// #3;

/* output:

@Alexis C. 2014-05-22 22:01:51

Or less cumbersome,;

@Boris the Spider 2014-09-20 09:11:49

This is clumsy. It should be System.out::println which is a Java 8 method reference. You code produces an unnecessary lambda.

@Justin 2016-03-04 23:16:07

Just skip the Arrays.asList and do

@Yassin Hajaj 2016-03-27 20:23:16

@AlexisC. Even better, Stream.of

@Alexis C. 2016-03-27 20:25:25

@YassinHajaj Why better?

@Yassin Hajaj 2016-03-27 20:27:10

@AlexisC. Because it can also be used with other objects than arrays.

@Alexis C. 2016-03-27 20:30:14

@YassinHajaj Yes, but the question specifically ask for an array. If you have an array, it's better to use than Stream.of.

@Yassin Hajaj 2016-03-27 20:31:11

@AlexisC. Is it better in terms of performance or just within the scope of this question?

@Alexis C. 2016-03-27 20:41:00

@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[], 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 will give you an IntStream directly.

@Alex 2018-02-19 17:35:33

Why use a Stream if you want to get a string? Especially if the Arrays class has a toString method?

@Akshay Hiremath 2019-12-14 22:26:18

Stream.of doesn't work well for array of primitive int

@Debosmit Ray 2016-03-11 11:50:38

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.

@sidgate 2016-08-10 11:48:25

you want to execute these if conditions on every object?

@YoYo 2017-09-11 15:52:57

+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 ...

@laylaylom 2015-12-23 18:51:48

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

@Haim Raman 2015-08-06 11:24:55

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


@Rhyous 2013-10-05 19:13:40

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.

@Scooter 2013-12-21 22:01:31

Maybe use System.getProperty("line.separator"); instead of \r\n so it is right for non-Windows as well.

@Novaterata 2017-04-07 17:20:34

you can use System.lineSeparator() now

@user3369011 2014-09-21 09:11:52

public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(;
        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) {

@Mohamed Idris 2015-02-17 08:02:36

A simplified shortcut I've tried is this:

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

It will print


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

@Jean Logeart 2014-02-18 20:21:26

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

Using Gson:

Gson gson = new Gson();

@Steve 2019-02-10 02:43:20

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.

@somedude 2011-01-24 04:25:54

for(int n: someArray) {
    System.out.println(n+" ");

@Matthias 2014-09-21 09:23:15

This way you end up with an empty space ;)

@Muhammad Suleman 2015-06-01 12:29:18

@ matthiad .. this line will avoid ending up with empty space System.out.println(n+ (someArray.length == n) ? "" : " ");

@NameNotFoundException 2015-07-08 12:56:07

Worst way of doing it.

@Radiodef 2018-08-06 22:02:18

@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.

@Roam 2014-04-29 07:34:31

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

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

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



@Andrew_Dublin 2013-12-27 23:31:15

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

@icza 2014-03-10 11:32:27

It prints "1, 2, 3, 4, 5, " as output, it prints comma after the last element too.

@Mona Jalal 2014-06-16 01:48:30

What's the solution for not having a comma after the last element?

@Nepoxx 2014-07-16 17:39:36

You could replace the code within the loop with System.out.print(intArray[i]); if(i != intArray.length - 1) System.out.print(", ");

@Nick Suwyn 2016-01-11 18:55:21

You could also use System.out.print(i + (i < intArray.length - 1 ? ", " : "")); to combine those two lines.

@Rick Ryker 2016-12-27 23:00:23

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

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] For-each over an array in JavaScript?

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6260723 View
  • 7817 Score
  • 93 Answer
  • Tags:   javascript arrays

49 Answered Questions

87 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

26 Answered Questions

25 Answered Questions

[SOLVED] How do I declare and initialize an array in Java?

  • 2009-07-29 14:22:27
  • bestattendance
  • 4382057 View
  • 1973 Score
  • 25 Answer
  • Tags:   java arrays

28 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1910368 View
  • 2219 Score
  • 28 Answer
  • Tags:   java arrays

34 Answered Questions

[SOLVED] Create ArrayList from array

3 Answered Questions

[SOLVED] Why is printing "B" dramatically slower than printing "#"?

30 Answered Questions

[SOLVED] How to append something to an array?

Sponsored Content