Unit 8: 2D Arrays
2D arrays store values in rows and columns. AP questions ask students to trace nested loops, calculate row/column totals, search grids, and check neighboring locations.
rowcolumnnested loopsgridmatrix
AP habit: trace values by hand before trusting your eyes. Most AP mistakes are loop bounds, type conversion, and reference mistakes.
Core Examples
Create a Grid
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]);Rows first, columns second.
Traverse All
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
System.out.println(grid[r][c]);
}
}Outer loop rows, inner loop columns.
Row Sum
int sum = 0;
int row = 1;
for (int c = 0; c < grid[row].length; c++) {
sum += grid[row][c];
}Fix row, vary column.
Try It in Java
Run and modify the examples below. Add print statements, change values, and test edge cases.
Code Tracing Drop-Down Practice
What is grid.length?
The number of rows.
What is grid[0].length?
The number of columns in row 0.
What is grid[1][2] in the example?
6.
Debugging Practice
Bug: using grid.length for columns.
Use grid[r].length or grid[0].length.
Bug: swapping row and column indexes.
Java uses grid[row][col].
AP-Style Multiple Choice
Which loop usually controls rows?
The outer loop.
How do you access row 2 column 3?
grid[2][3]
What type is one row of an int 2D array?
int[]
FRQ Practice
Write public static int columnSum(int[][] grid, int col) that returns the sum of values in the given column.Scoring focus
Look for the correct method signature, correct data use, clear control flow, and boundary-case handling.
Physics / Real-World Mini Project
Create a heat-map simulation. Store temperature values in a 2D array, calculate average temperature, hottest cell, and row/column summaries.