TOPIC 4.4 · STUDY
Array Traversals
An indexed loop for (int i = 0; i < a.length; i++) visits every element and can use the index. An enhanced for loop visits each value but does not give the index and does not replace a primitive element in the array. The condition i <= a.length walks one past the end.
4.4.A
Array traversals
A traversal walks through an array so each element is visited in a controlled order. The common indexed trip starts at 0 and stops before length: for (int i = 0; i < a.length; i++). Inside the body, a[i] is the element at that index, and i itself is available when you need the position.
int[] glow = {8, 1, 4};
for (int i = 0; i < glow.length; i++) {
System.out.print(glow[i]);
}
i takes 0, then 1, then 2. The body prints 8, then 1, then 4, so the console shows 814. Because i is the index, the same loop can also print i, compare neighbors with a[i] and a[i - 1], or write a new value into a[i].
The index starts at the first cell. Each update moves i one slot right until i reaches length.
Off-by-one errors show up in the Boolean test. The last legal index is a.length - 1. Writing i <= a.length lets i become equal to length, so a[i] reaches one past the end and throws ArrayIndexOutOfBoundsException. Starting at i = 1 with i < a.length skips index 0. Ending early, such as i < a.length - 1, skips the last element.
int[] glow = {8, 1, 4};
// i < glow.length visits 0, 1, 2
// i <= glow.length would try index 3 and crash
An enhanced for loop visits each value without an index: for (int n : glow). On each trip, n holds a copy of the current element. You can read n and print it, but assigning to n does not change the array slot. Replacing a primitive element requires an indexed loop that writes into a[i].
int[] glow = {8, 1, 4};
for (int n : glow) {
System.out.print(n);
}
for (int n : glow) {
n = 0;
}
System.out.print(glow[0]);
The first loop prints 814, the same left-to-right order as the indexed version when you only need the values. After the second loop, glow[0] is still 8 because n = 0 only updates the copy. Use for (int i = 0; i < glow.length; i++) { glow[i] = 0; } when you must clear or replace slots.
When the body needs the index, neighbors, or writes into a slot, stay with the indexed form. When the body only reads each value in order, an enhanced for is enough and can be rewritten as for (int i = 0; i < a.length; i++) with a[i] in place of the loop variable.
Key points
- for (int i = 0; i < a.length; i++) visits every element and provides the index.
- Inside that loop, a[i] is the element and i is its position.
- for (int n : a) visits each value in order but does not give an index.
- Assigning to the enhanced-for variable does not replace a primitive element.
- i <= a.length walks one past the last index and can throw an exception.
- Rewrite an enhanced for as an indexed for when you need a[i] writes or the index.
i < a.length stops at the last real index. Do not use i <= a.length for a full traversal.