Dump Multi-Dimensional Arrays in Java



A multi-dimensional array can be easily printed using java.util.Arrays.deepToString() in Java. This method converts the multi-dimensional array to string and prints the array contents enclosed in square brackets.

What Are Multi-Dimensional Arrays?

Multi-dimensional arrays allow you to store data in a matrix-like structure, providing a way to represent tables, grids, or more complex hierarchical data. The most common type is a two-dimensional array, but Java supports arrays with more than two dimensions.

int[][] array = new int[rows][columns];

Using Naive Approach

The Arrays.deepToString(arr) method from the Arrays class of java.util package prints the entire multi-dimensional array in a readable nested format.

Arrays.deepToString() method

Arrays.deepToString() method is used to print the array in a readable format. This method is particularly helpful for multi-dimensional arrays, as it handles nested structures gracefully.

Example

Below is the Java program to print multi-dimensional arrays ?

import java.util.Arrays;
public class Demo {
   public static void main(String args[]) {
      int arr [][]= { {5, 8, 6, 3}, {1, 9, 7}, {4, 8, 2}, {6} };
      System.out.println("The multi-dimensional array content is:");
      System.out.println(Arrays.deepToString(arr));
   }
}

Output

The multi-dimensional array content is:
[[5, 8, 6, 3], [1, 9, 7], [4, 8, 2], [6]]

Using Iterative Printing

Another way to work with multi-dimensional arrays is to iterate over them and print their contents. This approach provides more control and allows changes in the display format:

Iterative Access

  • A nested for loop is used to access each element of the multi-dimensional array.
  • The outer loop iterates over the rows, and the inner loop iterates over the elements within each row

This approach provides a row-by-row view of the array.

Example

Below is an example of printing multi-dimensional arrays using an iterative approach ?

public class Demo {
   public static void main(String args[]) {
      int arr[][] = {
         {5, 8, 6, 3},
         {1, 9, 7},
         {4, 8, 2},
         {6}
      };
      System.out.println("The multi-dimensional array content is:");


      for (int i = 0; i < arr.length; i++) {
         System.out.print("Row " + (i + 1) + ": ");
         for (int j = 0; j < arr[i].length; j++) {
            System.out.print(arr[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Output 

The multi-dimensional array content is:
Row 1: 5 8 6 3
Row 2: 1 9 7
Row 3: 4 8 2
Row 4: 6

Conclusion

Multi-dimensional arrays in Java are powerful and unique. Whether using built-in methods like Arrays.deepToString() or manual iteration, they provide flexible ways to represent and manipulate complex data structures.

Updated on: 2024-12-23T19:45:09+05:30

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements