Two-Dimensional Arrays
Traverse, search, and process 2D arrays by row, column, nested loop order, and rectangular dimensions.
A lesson of AP Computer Science A, in Arrays, ArrayLists, and 2D Arrays, about 10 minutes.
By the end of this lesson, you will be able to declare and initialize 2D arrays, traverse them with nested loops, and solve common 2D array problems.
Declaring and Creating 2D Arrays
int[][] matrix = new int[3][4]; // 3 rows, 4 columns; initialized to 0
// Literal initialization:
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements
int[][] grid = {{1,2,3},{4,5,6},{7,8,9}};
grid[0][0] // 1 (row 0, col 0)
grid[1][2] // 6 (row 1, col 2)
grid[2][1] // 8 (row 2, col 1)
// Dimensions:
grid.length // 3 (number of rows)
grid[0].length // 3 (number of columns in row 0)
Important: grid.length gives the number of rows, NOT columns. For columns, use grid[0].length (assuming rectangular array).
Traversal Patterns
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
Row-major order (standard):
Enhanced for loop (read-only):
for (int[] row : matrix) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
Common 2D Array Algorithms
int total = 0;
for (int[] row : matrix) {
for (int val : row) {
total += val;
}
}
Sum all elements:
Find max in entire array:
int max = matrix[0][0];
for (int[] row : matrix) {
for (int val : row) {
if (val > max) max = val;
}
}
Count elements meeting a condition:
int count = 0;
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] > 0) count++;
}
}
Column sum (need index-based loop):
// Sum of column 2:
int colSum = 0;
for (int row = 0; row < matrix.length; row++) {
colSum += matrix[row][2];
}
Ragged Arrays
int[][] triangle = new int[3][];
triangle[0] = new int[1]; // 1 column
triangle[1] = new int[2]; // 2 columns
triangle[2] = new int[3]; // 3 columns
Java 2D arrays can have rows of different lengths (ragged/jagged arrays).