Unit 4a: Arrays & 2D Arrays

Traversals, the off-by-one traps, and the row/column logic FRQ 4 always tests.

Unit 4 (Data Collections) is 30–40% of the exam — the largest chunk

Home → Unit 4a

Arrays: fixed size, indexed from 0

int[] nums = {4, 7, 1, 9};
nums.length        // 4 — no parentheses! (Strings use .length())
nums[0]            // 4 — first element
nums[nums.length - 1]   // 9 — last element, memorize this pattern
nums[4]            // 💥 ArrayIndexOutOfBoundsException

The two traversals — and when each one matters

// Standard for: you get the index. Use when position matters
// or you need to CHANGE elements.
for (int i = 0; i < nums.length; i++) {
    nums[i] *= 2;              // works — modifies the array
}

// Enhanced for (for-each): simpler, but n is a COPY.
for (int n : nums) {
    n *= 2;                    // does NOTHING to the array!
}

That second example is one of the most-tested facts in the unit: assigning to a for-each variable never changes the array (for objects, calling a method on the element does affect the real object — but reassigning doesn't).

2D arrays: rows first, then columns

int[][] grid = {
    {1, 2, 3},
    {4, 5, 6}
};
grid.length         // 2 — number of ROWS
grid[0].length      // 3 — number of COLUMNS
grid[1][2]          // 6 — row 1, column 2

// The standard nested traversal — row-major order:
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[0].length; c++) {
        System.out.print(grid[r][c] + " ");
    }
}   // prints: 1 2 3 4 5 6

Try it — exam-style questions

1. What does this print?
int[] a = {3, 8, 2, 5};
int max = a[0];
for (int i = 1; i < a.length; i++) {
    if (a[i] > max) max = a[i];
}
System.out.println(max);
2. After this runs, what is nums[1]?
int[] nums = {10, 20, 30};
for (int n : nums) {
    n = n + 5;
}
3. For int[][] m = new int[3][5]; which expression is the number of columns?
4. What does this print?
int[][] g = {{1, 2}, {3, 4}, {5, 6}};
int sum = 0;
for (int r = 0; r < g.length; r++) {
    sum += g[r][1];
}
System.out.println(sum);

⚠ Common mistakes that cost points

The 2D array FRQ doesn't have to be scary.

A few guided reps with someone who's graded hundreds of them turns FRQ 4 from a point-loser into a point-collector.

Ask about tutoring →