Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

Java Arrays.toString() and deepToString()

Reference for Arrays.toString() and Arrays.deepToString(): print arrays readably, handle nested arrays, null, and why printing an array directly fails.

An array's own toString() is inherited from Object, so System.out.println(array) prints a type code and an identity hash such as [I@6d06d69c. Arrays.toString() returns the readable form: the elements in square brackets separated by a comma and a space.

For arrays that contain other arrays, Arrays.toString() only prints each inner array's unhelpful identity string. Arrays.deepToString() walks nested arrays recursively and prints them all.

Java
Arrays.toString(new int[] {1, 2, 3});        // "[1, 2, 3]"
Arrays.deepToString(new int[][] {{1}, {2}}); // "[[1], [2]]"

Try it

Java Readable output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Nested arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public static String toString(int[] a)               // overloads for every primitive type and Object[]
public static String deepToString(Object[] a)
Name Description
a The array to describe. May be null.

Returns: a string like [a, b, c]. A null array gives "null"; an empty array gives "[]".

Throws: nothing for normal input. deepToString handles self-referencing arrays by printing [...] instead of recursing forever.

Usage notes

  • Use deepToString for arrays of arrays, including int[][]. toString on a 2D array prints the identities of the row arrays.
  • deepToString accepts Object[], so a one-dimensional int[] does not compile with it; use toString for that.
  • Elements are formatted with String.valueOf. Your own objects need a useful toString() (records have one for free).
  • char[] is special: System.out.println(char[]) prints the characters themselves, but string concatenation ("x" + chars) prints an identity. Use String.valueOf(chars) or new String(chars).
  • Alternatives: Arrays.asList(array).toString() works for object arrays; Arrays.stream(a).boxed().toList() works for primitives; String.join(",", strings) gives custom separators.
  • Not for parsing: the format is meant for humans and debugging output, not for storage.
  • Collections already print nicely: List, Set and Map have readable toString() methods.