Curriculum
In Java, a multi-dimensional array is an array that contains one or more arrays. A two-dimensional array, for example, is an array of arrays, where each sub-array is a one-dimensional array. A three-dimensional array is an array of arrays of arrays, and so on. Multi-dimensional arrays can be used to represent matrices, grids, and other data structures that have multiple dimensions.
Here’s an example of how to declare and initialize a two-dimensional array in Java:
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
In this example, the matrix array is a two-dimensional array with three rows and three columns. The sub-arrays represent the rows of the matrix, and the elements of each sub-array represent the columns of the matrix. The first element of the first row is 1, the second element of the third row is 8, and so on.
You can access an element of a multi-dimensional array using multiple index values. For example, to access the element in the second row and the third column of the matrix array, you would use the following code:
int element = matrix[1][2];
In this example, the first index value (1) represents the row of the element, and the second index value (2) represents the column of the element.
You can also initialize a multi-dimensional array without providing all the values. For example, to create a 3×3 array of zeros, you can use the following code:
int[][] matrix = new int[3][3];
In this example, the matrix array is created with a length of 3 in both dimensions, but all the elements are initialized to 0.
Multi-dimensional arrays can be used to represent more complex data structures with more than two dimensions. The syntax for declaring and initializing a multi-dimensional array with more than two dimensions is similar to the syntax for a two-dimensional array, but with additional pairs of square brackets to represent each additional dimension.