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. This post will discuss the difference between toString() and deepToString() method of the Arrays class in Java.
Arrays.toString() method
- The
toString()method of theArraysclass returns a string representation of the contents of the specifiedObjectarray. If the array contains other arrays as elements, they are converted to strings usingtoString()method of theObjectclass. - This method is widely used for converting single-dimensional
Objectarrays to strings. - This method doesn’t work on multidimensional arrays.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Arrays; class Main { public static void main(String[] args) { // single-dimensional Integer array Integer[] arr = { 1, 2, 3, 4, 5 }; // print string representation of the array System.out.println(Arrays.toString(arr)); } } |
Output:
[1, 2, 3, 4, 5]
Arrays.deepToString() method
- The
deepToString()method of theArraysclass returns string representation of the deep contents of the specifiedObjectarray. - Unlike
Arrays.toString(), if the array contains other arrays as elements, the string representation includes their contents and so on. - Unlike
Arrays.toString(), We can use it to convert multidimensional arrays to strings. - If the specified array contains a direct or indirect reference to itself, the self-reference is rendered as the string
"[...]"to avoid infinite recursion. - Unlike
Arrays.toString(), this method doesn’t work on an array of primitives.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Arrays; class Main { public static void main(String[] args) { Integer[] arr1 = { 1, 2, 3 }; Integer[] arr2 = { 4, 5 }; // two-dimensional Integer array Integer[][] arr = { arr1, arr2 }; // print string representation of the array using the `toString()` // method of the `Object` class System.out.println(Arrays.toString(arr)); // print string representation of the "deep contents" of the array System.out.println(Arrays.deepToString(arr)); } } |
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
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)