Signup/Sign In
PUBLISHED ON: JANUARY 21, 2021

Java Arrays deepToString() Method

In this tutorial, we will learn about deepToString() method in Java. This method accepts an array and it will convert the "deep content" of an array to a plain string. This method returns "null" if the specified array is null.

Syntax

This is the syntax of deepToString() method and from the syntax we can see it accepts an array and return a String.

public static String deepToString(Object[] a)

Example of deepToString() Method

In this example, we can clearly observe that given a two-dimensional array is converted to a normal String. In a string format, all the arrays are closed by "[" and "]" , all the elements of an array are separated by "," (comma).

import java.util.Arrays;
class StudyTonight { 
	public static void main(String args[]) 
	{ 
		int[][] array = {
				{ 8, 7, 4 }, 
				{ 3, 6, 5 },
				{ 0, 2, 1 } };
		System.out.println("Array in string format: "+Arrays.deepToString(array));
	} 
}


Array in string format: [[8, 7, 4], [3, 6, 5], [0, 2, 1]]

enlightenedWhy we are not using the toString() method instead of deepToString()? The reason is toString() method works well for one-dimensional array but fails on a multi-dimensional array.

Example of toString() with a multi-dimensional array

Compare the output of the following program with the output of the above example. We can find that toString() method doesn't work on a multi-dimensional array and that's why we use deepToString() method to convert the array to String.

import java.util.Arrays;
class StudyTonight { 
	public static void main(String args[]) 
	{ 
		int[][] array = {
				{ 8, 7, 4 }, 
				{ 3, 6, 5 },
				{ 0, 2, 1 } };
		System.out.println("Array in string format: "+Arrays.toString(array));
	} 
}


Array in string format: [[I@53bd815b, [I@2401f4c3, [I@7637f22]

Conclusion:

In this tutorial, we learned how to convert a multi-dimensional array using deepToString() method. We also learned toString() method doesn't work on multidimensional arrays.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.