Arrays.deepToString for Multidimensional Arrays
What You'll Learn
You'll learn how to convert nested (multidimensional) arrays into readable strings using Arrays.deepToString().
The Problem with toString() for Nested Arrays
You already know Arrays.toString() works great for single-dimensional arrays. But what happens when you try it on a 2D array? You get something unhelpful like [[I@15db9742, [I@6d06d69c] — memory addresses, not the actual values!
This happens because toString() only looks one level deep. Each element in your outer array is itself an array reference, which prints as a memory address.
Enter Arrays.deepToString()
Arrays.deepToString() solves this by recursively converting nested arrays at any depth into a readable string format. It dives into each level of your array structure and formats everything nicely.
Syntax:
String result = Arrays.deepToString(arrayName);
Example with a 2D array:
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.deepToString(grid));
// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Example with a jagged array:
int[][] jagged = {
{1, 2},
{3, 4, 5, 6},
{7}
};
System.out.println(Arrays.deepToString(jagged));
// Output: [[1, 2], [3, 4, 5, 6], [7]]
Think of It Like This
Imagine a filing cabinet with folders inside folders. toString() only reads the folder labels. deepToString() opens every folder and reads all the documents inside, no matter how many levels deep.
Key Takeaway: Use Arrays.deepToString() whenever you need to visualize or debug multidimensional arrays — it handles nested structures of any depth automatically.