Arrays.deepToString() Method in Java - Quiz

Total: 5 questions

1. 

What does the Arrays.deepToString() method do, and what is its signature?

The method public static String deepToString(Object[] a) from the java.util.Arrays class returns a string representation of a multidimensional array. It recursively walks through the nested arrays and wraps every nesting level in square brackets. It is the shortest way to print a 2D or multidimensional array to the console without writing loops.

2. 

How does Arrays.deepToString() differ from Arrays.toString()?

Arrays.toString() processes only the first level of the array: each element is converted by calling its own toString(). For a 2D array the first-level elements are the nested arrays, and arrays do not override toString() — so you get the type and hash code, e.g. [[Ljava.lang.String;@1b6d3586, ...]. Arrays.deepToString() traverses the array recursively and prints the contents of every nesting level.

3. 

Can you pass a one-dimensional int[] and a two-dimensional int[][] array to deepToString()?

A one-dimensional int[] cannot be passed: the code will not compile because int[] is not convertible to Object[]. For one-dimensional primitive arrays there are Arrays.toString() overloads. An int[][], however, can be passed: its first-level elements are objects of type int[], so the array is compatible with the Object[] parameter, and the output looks like [[1, 2, 3], [4, 5, 6]].

4. 

What does deepToString() return if the array is null, contains null elements, or references itself?

If the argument is null, the method returns the string "null". Nested null elements are also printed as null. If the array directly or indirectly contains a reference to itself, "[...]" is printed in that place instead of infinite recursion — for example, [first, [...]].

5. 

Besides deepToString(), which companion methods of the Arrays class use "deep" semantics for multidimensional arrays?

For comparing and hashing multidimensional arrays, the Arrays class offers Arrays.deepEquals() and Arrays.deepHashCode(). Like deepToString(), they traverse all nesting levels recursively, unlike the "shallow" Arrays.equals() and Arrays.hashCode().

Page 1 of 1