One-Dimensional Arrays and Traversals

AP Computer Science A · Unit 4 — Data Collections

Fixed length, zero-based indexing

An array holds a fixed number of values of the same type. The length is decided when the array is created and can never change: int[] a = new int[6]; creates six slots, and a.length is 6 forever. Note that length is a field, not a method — there are no parentheses, unlike String.length().

Valid indices run from 0 to a.length − 1. Touching any other index throws an ArrayIndexOutOfBoundsException at run time — the compiler will not catch it.

New arrays are filled with default values: 0 for int, 0.0 for double, false for boolean, and null for object types such as String.

Two ways to traverse

for (int i = 0; i < a.length; i++) {   // indexed loop
    a[i] = a[i] * 2;                     // CAN modify
}

for (int x : a) {                        // enhanced for (for-each)
    System.out.println(x);               // read only
}

The enhanced for loop copies each element into the loop variable. Assigning to that variable changes the copy, never the array. Use the indexed loop whenever you must write into the array, compare neighbouring elements, or know where you are.

int[] a = new int[6]; → a.length = 6 0 1 2 3 4 5 6 valid indexes: 0 .. a.length − 1 cell does not exist for (int i = 0; i < a.length; i++) — stops EXACTLY at this line i <= a.length → touches cell 6 → ArrayIndexOutOfBoundsException
Where the stopping line sits. There are six cells but the largest index is 5 — the number 6 is a count, not an address. That is why the loop condition must be i < a.length; changing it to i <= a.length makes the loop run exactly one extra beat into a cell that does not exist. This is the off-by-one error, and it is not wrong on every run but only on the last beat, so careless testing easily misses it.

Worked example: comparing adjacent elements

Write code that counts how many times an element of the array int[] a is greater than the element right after it, then explain why a for-each loop cannot be used.

Solution

int dem = 0;
for (int i = 0; i < a.length - 1; i++) {
    if (a[i] > a[i + 1]) {
        dem++;
    }
}

Why a.length - 1. The loop body touches a[i + 1], so the largest index i may take is a.length - 2. General principle: the largest index touched in the loop body determines the stopping condition, not the index of the loop variable.

Why not for-each. A for-each loop hands us only the value of the current element, not its position, so there is no way to ask “what is the element right after it”. Every problem that looks at two elements at the same time requires indexes.

With a = {3, 8, 1, 6, 2} the code returns 2, corresponding to the two pairs (8, 1) and (6, 2).

Common mistake

The two one-dimensional array errors that cost the most points, and how to prevent each. One: i <= a.length. How to prevent it — before writing the stopping condition, read the loop body and ask “what is the largest index touched”; if it touches a[i + 1], stop at a.length - 1; if it touches a[i], stop at a.length. Two: using for-each, assigning to the loop variable, and thinking the array changes with it. How to prevent it — set a rule for yourself: whenever the loop body contains an = sign writing to an element, immediately switch to an indexed loop.

Key takeaway

Fixed length, indexes from 0 to length - 1, and length has no parentheses. When you need to write or need to know the position, use an index; for reading only, for-each is more compact and cannot break.

← Polymorphism, the Object Class, and is-a versus has-a · All AP Computer Science A lessons · Practice AP Computer Science A questions (free, instant scoring) · ArrayList and Safe Removal →