What Are Multidimensional Arrays?
A multidimensional array is essentially an array of arrays. This can be particularly useful when you need to store data in a tabular format, like a table with rows and columns.
Creating a Two-Dimensional Array
To create a two-dimensional array, you simply nest each array within its own set of curly braces:
int[][] garage = { {1, 2, 3, 4}, {5, 6, 7} };
Here, garage
is now an array containing two arrays as its elements.
Accessing Elements
To access the elements of the garage
array, you specify two indexes: one for the array and one for the element inside that array. For example, to access the third element in the second array:
int[][] garage = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(garage[1][2]); // Outputs 7
Note: Array indexes start at 0, so [0]
is the first element, [1]
is the second element, and so on.
Modifying Element Values
You can also change the value of an element in a multidimensional array:
int[][] garage = { {1, 2, 3, 4}, {5, 6, 7} };
garage[1][2] = 9;
System.out.println(garage[1][2]); // Outputs 9 instead of 7
Looping Through a Multidimensional Array
Using Nested For Loops
To iterate through a two-dimensional array, you can use a for
loop inside another for
loop:
int[][] garage = { {1, 2, 3, 4}, {5, 6, 7} };
for (int row = 0; row < garage.length; ++row) {
for (int col = 0; col < garage[row].length; ++col) {
System.out.println(garage[row][col]);
}
}
Using For-Each Loops
Alternatively, you can use a for-each
loop, which is often easier to read and write:
int[][] garage = { {1, 2, 3, 4}, {5, 6, 7} };
for (int[] row : garage) {
for (int element : row) {
System.out.println(element);
}
}