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.
Arrays.toString(new int[] {1, 2, 3}); // "[1, 2, 3]" Arrays.deepToString(new int[][] {{1}, {2}}); // "[[1], [2]]"
Try it
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.
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
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
deepToStringfor arrays of arrays, includingint[][].toStringon a 2D array prints the identities of the row arrays. deepToStringacceptsObject[], so a one-dimensionalint[]does not compile with it; usetoStringfor that.- Elements are formatted with
String.valueOf. Your own objects need a usefultoString()(records have one for free). char[]is special:System.out.println(char[])prints the characters themselves, but string concatenation ("x" + chars) prints an identity. UseString.valueOf(chars)ornew 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,SetandMaphave readabletoString()methods.
Related
- Arrays, Arrays.asList(), Object, String.join()
- Lessons: Arrays, Multidimensional arrays