The Arrays class is a member of the Java Collections Framework and contains various static utility methods for array manipulation. This post will discuss the difference between toString() and deepToString() method of the Arrays class in Java.

Arrays.toString() method

  1. The toString() method of the Arrays class returns a string representation of the contents of the specified Object array. If the array contains other arrays as elements, they are converted to strings using toString() method of the Object class.
  2. This method is widely used for converting single-dimensional Object arrays to strings.
  3. This method doesn’t work on multidimensional arrays.

The following program demonstrates it:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

Arrays.deepToString() method

  1. The deepToString() method of the Arrays class returns string representation of the deep contents of the specified Object array.
  2. Unlike Arrays.toString(), if the array contains other arrays as elements, the string representation includes their contents and so on.
  3. Unlike Arrays.toString(), We can use it to convert multidimensional arrays to strings.
  4. If the specified array contains a direct or indirect reference to itself, the self-reference is rendered as the string "[...]" to avoid infinite recursion.
  5. Unlike Arrays.toString(), this method doesn’t work on an array of primitives.

The following program demonstrates it:

Download  Run Code

Output:

[[Ljava.lang.Integer;@1540e19d, [Ljava.lang.Integer;@677327b6]
[[1, 2, 3], [4, 5]]

That’s all about differences between the Arrays.toString() and Arrays.deepToString() in Java.

 
Reference: Arrays class – Javadoc SE 9