Java - Array - Part 2

Multidimensional arrays in Java are essentially arrays of arrays. They allow you to store multiple sets of data in an organized manner. You can think of a 2D array as a table with rows and columns, while a 3D array can be thought of as a cube with layers, rows, and columns.

To declare a multidimensional array in Java, you specify the number of rows and columns in the array, separated by a comma. For example, to declare a 2D array of integers with 3 rows and 4 columns, you would write:

int[][] array = new int[3][4];

You can also declare and initialize a multidimensional array in one line:

int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

To access an element in a 2D array, you specify the row and column index:

int element = array[1][2]; // retrieves the element in row 1, column 2 (which has the value 6 in the example above)

To loop through a multidimensional array, you typically use nested loops. For example, to loop through a 2D array and print out all of its elements, you would write:

 

for (int i = 0; i < array.length; i++) {
  for (int j = 0; j < array[i].length; j++) {
    System.out.print(array[i][j] + " ");
  }
  System.out.println(); // prints a newline after each row
}

In this example, the outer loop iterates over the rows of the array, while the inner loop iterates over the columns of each row. The System.out.print() method is used to print each element, followed by a space. After printing all the elements in a row, a newline is printed to move on to the next row.

You can extend this concept to loop through higher-dimensional arrays as well. For example, to loop through a 3D array and print out all of its elements, you would add an additional loop:

for (int i = 0; i < array.length; i++) {
  for (int j = 0; j < array[i].length; j++) {
    for (int k = 0; k < array[i][j].length; k++) {
      System.out.print(array[i][j][k] + " ");
    }
  }
  System.out.println();
}

In this example, the outermost loop iterates over the "layers" of the array, the middle loop iterates over the rows of each layer, and the innermost loop iterates over the columns of each row.