Multidimensional Arrays
Java Multi-Dimensional Arrays
An array of arrays is a multidimensional array.
When you wish to store data in a tabular format, such as a table with rows and columns, multidimensional arrays come in handy.
Add each array within a separate set of curly brackets to produce a two-dimensional array:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
MyNumbers is now an array whose elements are two arrays.
Access Elements
You must provide two indexes—one for the array and another for the element contained within the myNumbers array—in order to access the elements of that array. The third element (2) in the second array (1) of myNumbers is accessed in this example:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7
Keep in mind that: Array indexes begin at 0: The first element is [0]. The second element is [1], and so on.
Change Element Values
Additionally, you can alter an element’s value:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
Loop Through a Multi-Dimensional Array
To obtain the items of a two-dimensional array, you can also use a for loop inside another for loop (we still need to point to the two indexes):
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for (int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
Alternatively, you could just use a for-each loop, which is thought to be simpler to write and read:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int[] row : myNumbers) {
for (int i : row) {
System.out.println(i);
}
}