Arrays.toString() vs Arrays.deepToString() in Java

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


 

Arrays.toString()

1. The toString() method of the Arrays class returns 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 array of primitives and multi-dimensional arrays.

 

Download Run Code

Output:

[1, 2, 3, 4, 5]

 

Arrays.deepToString()

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(), it can be used to convert multi-dimensional 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. Like Arrays.toString(), this method doesn’t work on array of primitives.

 

Download   Run Code

Output:

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

 
References: Arrays class – Javadoc SE 9

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of