A multidimensional array in Java is essentially an array of arrays. This means that each element of the array is itself an array. Multidimensional arrays can be two-dimensional, three-dimensional, or even higher-dimensional.
Here’s an example of how to declare, initialize, and access elements in a two-dimensional array in Java:
public class MultidimensionalArrayExample { public static void main(String[] args) { // Declare and initialize a 2D array int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Access and print elements of the 2D array System.out.println("2D Array:"); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
In this example, `matrix` is a two-dimensional array with three rows and three columns. We initialize it with some values. To access elements of the 2D array, we use nested loops. The outer loop iterates over the rows, and the inner loop iterates over the columns within each row.
Output:
2D Array: 1 2 3 4 5 6 7 8 9
You can extend this concept to create higher-dimensional arrays by adding additional dimensions to the array declaration and initialization. For example, a three-dimensional array would be declared as `int[][][]` and initialized accordingly. Accessing elements in higher-dimensional arrays requires nested loops for each dimension.