Multidimensional Array
In Java, a multidimensional array is an array that contains one or more arrays. A two-dimensional array is the most common type of multidimensional array, and can be thought of as an array of arrays.
To declare a two-dimensional array in Java, you use the following syntax:
type[][] arrayName = new type[numRows][numCols];
For example, to declare a two-dimensional integer array that has 3 rows and 4 columns, you would use the following code:
int[][] matrix = new int[3][4];
To initialize the elements of a two-dimensional array, you can use nested loops to iterate over the rows and columns:
for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { matrix[row][col] = row * col; } }
This code initializes the elements of the matrix
array with the value of row * col
.
You can access the elements of a two-dimensional array using two indices, one for the row and one for the column:
int value = matrix[2][3]; // Gets the value of the element in the third row and fourth column
In Java, you can also create arrays with more than two dimensions by adding additional pairs of square brackets. For example, a three-dimensional array can be declared and initialized like this:
int[][][] cube = new int[3][4][5];
This creates a three-dimensional array of integers with dimensions 3 x 4 x 5. Initializing and accessing elements in a three-dimensional array is similar to a two-dimensional array, but with an additional index for the third dimension.
Multidimensional arrays are useful for storing and manipulating data that has more than one dimension, such as images, matrices, and game boards.