Multidimensional Arrays
A cinema hall's seats are a grid: rows A, B, C, and seats 1, 2, 3, 4 in each row. A class's marks are a table: one row per student, one column per subject. When data has rows and columns, Java stores it in a two-dimensional (2D) array, and you reach each value with two indexes: [row][column].
A Marks Table
public class MarksTable {
public static void main(String[] args) {
int[][] marks = {
{78, 92, 85},
{88, 79, 94},
{65, 70, 72}
};
System.out.printf("Rows: %d, columns: %d%n",
marks.length, marks[0].length);
System.out.println("Row 1, subject 2: " + marks[1][2]);
}
}Rows: 3, columns: 3
Row 1, subject 2: 94How it works
- Lines 3 to 7 create a 3 × 3 table: each inner
{...}is one row. marks.lengthis the number of rows;marks[0].lengthis the number of columns in row 0.- Line 10:
marks[1][2]means row 1, column 2, both counted from 0, so it's the second student's third subject: 94.
Try it yourself: print marks[2][0]. Which student and which subject is that?
Rows, Columns, and an Array of Arrays
In Java, a 2D array is really an array of arrays: marks holds 3 references, and each points to a separate row array. That's why marks[1] is itself an array, with its own length, and why rows can even have different lengths (see "Jagged Arrays").
Creating an Empty Grid
public class Seats {
public static void main(String[] args) {
boolean[][] booked = new boolean[3][4];
booked[1][2] = true;
for (int row = 0; row < booked.length; row++) {
for (int seat = 0; seat < booked[row].length; seat++) {
System.out.print(booked[row][seat] ? "X " : "- ");
}
System.out.println();
}
}
}- - - -
- - X -
- - - -new boolean[3][4] makes 3 rows of 4 seats, every one false by default. The nested loops (see "Nested Loops") visit every seat: the outer loop picks the row, the inner loop goes along it.
Row Totals
public class RowTotals {
public static void main(String[] args) {
String[] names = {"Navika", "Srihitha", "Advitha"};
int[][] marks = {{78, 92, 85}, {88, 79, 94}, {65, 70, 72}};
for (int r = 0; r < marks.length; r++) {
int total = 0;
for (int mark : marks[r]) {
total += mark;
}
System.out.println(names[r] + ": " + total);
}
}
}Navika: 255
Srihitha: 261
Advitha: 207The inner loop is a for-each over one row: marks[r] is an int[], so it works like any other array.
Common Mistakes
Swapping row and column. marks[2][1] and marks[1][2] are different cells. Decide once that the first index is the row.
Using marks.length for the columns. That's the number of rows. Use marks[row].length.
More than two dimensions without need. Java allows int[][][], but three-level loops are hard to follow. Consider objects instead (Level 2).
Practice
- Easy: Print the total of each column (each subject) of the marks table.
- Harder: Create a 4 × 4 grid and fill it so
grid[i][j] = i * j, then print it as a table withprintf("%4d", ...).
Key Takeaways
Was this tutorial helpful?