java.util.Arrays deepToString()


On this document we will be showing a java example on how to use the deepToString() method of Arrays Class. Basically the deepToString() method returns returns a string representation of the “deep contents” of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings. As you would have remembered we have also a method under Arrays class that gives a string representation of an array which is the toString() method. However the toString() method is only applicable to one dimensional array, but the deepToString() method comes into play to overcome this deficiency.

As a reference we can say that both array are deeply equals to each other if both are null or they have the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.

Method Syntax

public static String deepToString(Object[] a)

Method Argument

Data Type Parameter Description
Object[] a the array whose string representation to return

Method Returns

The deepToString() method returns a string representation of a.


Requires Java 1.5 and up

Java Arrays deepToString(Object[] a) Example

Below is a java code demonstrates the use of deepToString() method of Arrays class. The example presented might be simple however it shows the behaviour of the deepToString() method.


import java.util.Arrays;

 * A java example source code to demonstrate
 * the use of deepToString() method of Arrays class

public class ArraysDeepToStringExample {

	public static void main(String[] args) {

		// initialize a new String array
		String[] names = new String[]{
		System.out.println("******One dimensional array******");
		// get the String representation
		System.out.println("******Multi dimensional array******");
		// get String representation multi dimensional array
		int[][] value = new int[2][2];
		value[0][0] = 1;
		value[0][1] = 2;
		value[1][0] = 3;
		value[1][1] = 4;

		// print using toString() method
		System.out.println("Print using toString()");
		// print using deepToString() method
		System.out.println("Print using deepToString()");

Basically we initialize a one dimensional array and prints out the Array representation of this array using toString(). At this point the toString() method will work. However on the later part of our example we have initialize another array value and then we printed out the string equivalent of it using the toString() method. At this stage you would have noticed that the printed string is the hashcode of the objects inside the first layer of array which we would not be interested with. Then we use the deepToString() method to print out the values of our array, and this will give a more readable print out.

Sample Output

Below is the sample output when you run the above example.

Arrays deepToString() example output