Method Arrays.deepToString()

Author: Tatyana Milkina

The Arrays.deepToString() method in Java returns a readable string representation of multidimensional arrays. Unlike Arrays.toString(), which is designed for one-dimensional arrays only, this method correctly formats nested arrays using square brackets to reflect the array structure.

Here’s an example showing how to use Arrays.deepToString() with a two-dimensional String array:

import java.util.Arrays;

public class ArraysDeepToStringExample {
    public static void main(String[] args) {
        String[][] array = {
            {"one-one", "one-two", "one-three"},
            {"two-one", "two-two", "two-three"}
        };
        System.out.println(Arrays.deepToString(array));
    }
}

Output:

[[one-one, one-two, one-three], [two-one, two-two, two-three]]

This method is extremely useful for debugging Java arrays or when you need to output a clear view of data structures such as tables, matrices, or nested collections.

For higher-dimensional arrays, Arrays.deepToString() continues to recursively format all inner arrays. It prevents common mistakes like printing memory addresses instead of actual values.

If you try to print a multidimensional array with Arrays.toString(), you'll get results like:

[[Ljava.lang.String;@6d06d69c, [Ljava.lang.String;@7852e922]

This happens because the inner arrays are treated as objects. Always use deepToString() for nested arrays.

Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments