AP Computer Science A · Unit 4: Data Collections
4.2 Traversing Arrays
Traversing with a for loop
To visit every element in an array, use a `for` loop with an index variable that runs from `0` to `array.length - 1`. This gives access to each index and its value, and lets you modify elements in place, e.g. `for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] * 2; }`.
Enhanced for loop (for-each)
The enhanced for loop simplifies traversal when you only need each *value*, not the index: `for (int x : arr) { System.out.println(x); }`. It's cleaner but you cannot modify the original array elements through it, since `x` is a copy of each value.
Common traversal errors
Using `<=` instead of `<` in the loop condition causes an ArrayIndexOutOfBoundsException, since valid indices only go up to `array.length - 1`. Off-by-one mistakes are the most frequent bug when traversing arrays, so always double check loop bounds.
Key terms
- Standard for loop traversal
- for (int i = 0; i < arr.length; i++) — gives access to both index and value, allows modification of elements.
- Enhanced for loop
- for (type x : arr) — iterates over values only; cannot modify original array elements.
- arr.length
- A field (not a method) that returns the number of elements in array arr.
- Off-by-one error
- A common bug from using <= instead of < in loop conditions, leading to out-of-bounds access.
- ArrayIndexOutOfBoundsException
- Runtime error thrown when accessing an index outside the valid range (0 to length - 1).
Try an AP-style question
Code
int[] a = {3, 8, 2, 5};
int s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];What is s?
- 13
- 18
- 8
- 5
Show the answer
B. 3 + 8 + 2 + 5.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 4.2 free in APrep