Multidimensional Arrays in Java

In Java, multidimensional arrays are arrays of arrays. They can be used to represent tables, matrices, or any other data structures with multiple dimensions. Let's explore multidimensional arrays in-depth.

Declaration of Multidimensional Arrays:

Multidimensional arrays are declared by specifying the data type of the elements followed by multiple sets of square brackets.


// Declaration of a 2D integer array
int[][] twoDArray;

// Declaration of a 3D string array
String[][][] threeDArray;

Initialization of Multidimensional Arrays:

Multidimensional arrays can be initialized during declaration or later using the new keyword.

1. Initializing during declaration:


// Initializing a 2D integer array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

// Initializing a 3D string array
String[][][] cube = {{{"A", "B"}, {"C", "D"}}, {{"E", "F"}, {"G", "H"}}};

2. Initializing later with new keyword:


// Declaring a 2D integer array
int[][] twoDArray;

// Initializing the 2D array later
twoDArray = new int[3][4]; // 3 rows, 4 columns

Accessing Elements of Multidimensional Arrays:

Elements of multidimensional arrays are accessed using indices for each dimension.


// Accessing an element of a 2D array
int element = matrix[1][2]; // Row 1, Column 2


// Accessing an element of a 3D array
String value = cube[0][1][0]; // Layer 0, Row 1, Column 0

Iterating Through Multidimensional Arrays:

Nested loops are used to iterate through the elements of multidimensional arrays.


// Iterating through a 2D array
for (int i = 0; i < matrix.length; i++) {
  for (int j = 0; j < matrix[i].length; j++) {
    int element = matrix[i][j];
    // Process the element as needed
  }
}


// Iterating through a 3D array
for (int i = 0; i < cube.length; i++) {
  for (int j = 0; j < cube[i].length; j++) {
    for (int k = 0; k < cube[i][j].length; k++) {
      String element = cube[i][j][k];
      // Process the element as needed
    }
  }
}

Note:

Multidimensional arrays in Java are flexible and can be used to represent various data structures. Pay attention to the indices for each dimension while accessing elements.