Multidimensional Arrays
A two-dimensional array is an array of arrays — perfect for grids, tables, game boards and matrices. Java's multidimensional arrays can even have rows of different lengths.
Creating a 2D array
JAVA
void main() { int[][] grid = { {1, 2, 3}, {4, 5, 6} }; System.out.println(grid[0][2]); System.out.println(grid[1][0]); System.out.println("Rows: " + grid.length + ", columns: " + grid[0].length); }
Output
3 4 Rows: 2, columns: 3
grid[row][column]: the first index picks the row (an inner array), the second the element within it.
Looping over rows and columns
JAVA
void main() { int[][] seats = new int[3][4]; seats[1][2] = 1; seats[2][0] = 1; for (int r = 0; r < seats.length; r++) { for (int c = 0; c < seats[r].length; c++) { System.out.print(seats[r][c] == 1 ? "X " : ". "); } System.out.println(); } }
Output
. . . . . . X . X . . .
new int[3][4] creates 3 rows of 4 zeros. Use seats[r].length for the inner loop so it works even when rows differ in length.
for-each over a 2D array
JAVA
void main() { int[][] scores = { {80, 92, 75}, {66, 70, 88}, {95, 99, 91} }; int student = 1; for (int[] row : scores) { int sum = 0; for (int s : row) sum += s; System.out.println("Student " + student++ + " average: " + sum / row.length); } }
Output
Student 1 average: 82 Student 2 average: 74 Student 3 average: 95
Jagged arrays
JAVA
import java.util.Arrays; void main() { int[][] triangle = new int[5][]; for (int i = 0; i < triangle.length; i++) { triangle[i] = new int[i + 1]; triangle[i][0] = 1; triangle[i][i] = 1; for (int j = 1; j < i; j++) { triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; } } for (int[] row : triangle) { System.out.println(Arrays.toString(row)); } }
Output
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1]
Because a 2D array is an array of arrays, each row can have its own length. Here the rows of Pascal's triangle grow by one each time.
Printing with deepToString
JAVA
import java.util.Arrays; void main() { char[][] board = { {'X', 'O', 'X'}, {' ', 'X', 'O'}, {'O', ' ', 'X'} }; System.out.println(Arrays.deepToString(board)); }
Output
[[X, O, X], [ , X, O], [O, , X]]
Matrix arithmetic
JAVA
import java.util.Arrays; void main() { int[][] a = {{1, 2}, {3, 4}}; int[][] b = {{5, 6}, {7, 8}}; int[][] product = new int[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { product[i][j] += a[i][k] * b[k][j]; } } } System.out.println(Arrays.deepToString(product)); }
Output
[[19, 22], [43, 50]]
Try it yourself
Check whether a tic-tac-toe board has a winning row.
Output
X wins on row 2