Unit 8: 2D Array
AP Computer Science A: 51 practice questions with detailed explanations.
Unit Study Guide
Executive Summary
A 2D array is an array of arrays — a grid of rows, each row its own 1D array.
Creation and dimensions
int[][] grid = new int[rows][cols] makes a rectangle. grid.length is the number of rows; grid[r].length is the number of columns in row r. Access elements as grid[r][c] — row first, column second.
Traversals
Row-major order: outer loop over rows, inner over columns. Column-major swaps them. The inner condition should use grid[r].length so ragged arrays work. Enhanced for yields whole rows: for (int[] row : grid).
Algorithms
Sum or count with nested loops and an accumulator. Find max by comparing every element. Diagonal elements have r == c in a square grid; one loop suffices to sum them. Doubling every element needs indexed assignment — enhanced for cannot write.
Ragged arrays
Rows can have different lengths. Always read grid[r].length inside the loop rather than grid[0].length when rows may differ.
Exam traps
grid.length counts rows, not total elements. grid[r][c] vs grid[c][r] transposes the grid. Accessing grid[rows][0] or grid[0][cols] throws ArrayIndexOutOfBoundsException.