Java Multi-Dimensional Arrays: Storing Data in Tabular Form
Understand how to use multi-dimensional arrays in Java to store data in a table-like structure with rows and columns. Learn how to create a two-dimensional array by nesting arrays within curly braces, and efficiently manage complex data in your Java programs.
Java Multi-Dimensional Arrays
A multidimensional array is an array of arrays, useful for storing data in a tabular form like a table with rows and columns.
Creating a Two-Dimensional Array
To create a two-dimensional array, enclose each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
Accessing Elements
To access elements, specify two indexes: one for the array and one for the element inside that array:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7
Output
7
Changing Element Values
You can change the value of an element in a multidimensional array:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9
Output
9
Looping Through a Multi-Dimensional Array
You can use nested loops to iterate through a two-dimensional array:
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]);
}
}
Output
1
2
3
4
5
6
7
Alternatively, you can use a for-each loop for easier readability:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int[] row : myNumbers) {
for (int i : row) {
System.out.println(i);
}
}