Traversals, the off-by-one traps, and the row/column logic FRQ 4 always tests.
Home → Unit 4a
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
// 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).
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
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);
nums[1]?int[] nums = {10, 20, 30};
for (int n : nums) {
n = n + 5;
}
int[][] m = new int[3][5]; which expression is the number of columns?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);
i <= a.length in a loop bound — instant out-of-bounds crash. It's <..length (arrays, no parens) with .length() (Strings) and .size() (ArrayList).[row][col] above your work and stick to it.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 →