AP Computer Science A · Study guide

Array Traversals

Unit 4 · Data Collections · Topic 4.4

Array Traversals

The hidden assignment inside every enhanced for loop — why it can never write into an array, and why it can still change every object an array points at.

Exam-day recap
  • Traversing an array uses repetition to access all or an ordered sequence of elements.
  • Indexed for and while loops reach elements using their indices.
  • An array of length 5 has indices 0 to 4; i <= 5 tries index 5 and throws ArrayIndexOutOfBoundsException.
  • The enhanced for loop variable is assigned a copy of each element without using its index.
  • Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
  • To write into an array you need the index: seeing[i] = seeing[i] * 2; is the slot itself.
  • For object arrays, calling a method on the loop variable changes the object but not the stored references.
  • A dot changes the object; an equals sign changes nothing.
  • Any enhanced for loop can be rewritten as indexed or while, but the reverse is not always possible.

1What Traversal Means

An observatory logs the seeing — how steady the air is, in arc-seconds — once an hour through the night. Five readings, and something to be done with each one.

double[] seeing = {1.8, 1.2, 2.4, 0.9, 1.5};
Essential knowledge 4.4.A.1

Traversing an array is when repetition statements are used to access all or an ordered sequence of elements in an array.

Two words in that sentence are doing work. Repetition — a loop, not five separate lines. Ordered sequence — a traversal does not have to visit everything; a loop over the first three, or every second element, or the array backwards is still a traversal.

There are three ways to write one, and the course expects all three:

FormGives youCan write into the array?
Indexed forThe index, and the element through itYes
whileThe same, with the counter written out separatelyYes
Enhanced forA copy of each element, and no indexNo

2The Indexed for Loop

Essential knowledge 4.4.A.2

Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.

for (int i = 0; i < seeing.length; i++)
{
   System.out.println(seeing[i]);
}

The loop counts; the array is reached through seeing[i]. Three parts carry all the risk:

PartWrittenGetting it wrong
Startint i = 0Starting at 1 silently skips the first element
Conditioni < seeing.length<= runs one past the end and throws
Updatei++Forgetting it is an infinite loop
Why it is < and not <=

An array of length 5 has indices 0 to 4. i < 5 stops after 4; i <= 5 tries index 5, which does not exist, and throws ArrayIndexOutOfBoundsException on the last pass — after the loop has already printed everything, which is what makes it confusing to read.

2.1 The while Loop Is the Same Thing, Spread Out

int i = 0;
while (i < seeing.length)
{
   System.out.println(seeing[i]);
   i++;
}

Identical behavior. The three parts have moved: the start is above the loop, the condition is in the header, and the update is the last line of the body. That last move is where while loops break — an if that skips the i++, or a continue above it, and the loop never ends.

3The Enhanced for Loop

Essential knowledge 4.4.A.3

An enhanced for loop header includes a variable, referred to as the enhanced for loop variable. For each iteration, the enhanced for loop variable is assigned a copy of an element without using its index.

for (double s : seeing)
{
   System.out.println(s);
}

Read the colon as “taken from”. On each pass, s is a fresh variable holding a copy of the next element. There is no counter and no [] anywhere in it.

3.1 The Hidden Assignment

The exact wording of 4.4.A.3 is worth taking literally. Every iteration performs an assignment that is not written in the code:

// what the enhanced for loop does, spelled out
for (int i = 0; i < seeing.length; i++)
{
   double s = seeing[i];   // ← this line is the whole point
   System.out.println(s);
}
Write that line in the margin

Almost every enhanced-for question is answered by writing double s = seeing[i]; and then asking what happens to s. If the code assigns to it, the copy changes. If the code calls a method on it, the object it references changes. The two are different, and the hidden line makes it obvious which one is happening.

4Assigning to the Loop Variable Changes Nothing

Essential knowledge 4.4.A.4

Assigning a new value to the enhanced for loop variable does not change the value stored in the array.

for (double s : seeing)
{
   s = 0.0;      // changes the copy, and only the copy
}
// seeing is still {1.8, 1.2, 2.4, 0.9, 1.5}

The assignment succeeds — it compiles, it runs, and s really does become 0.0. It is simply a different variable from the array slot. The next iteration overwrites s with the next copy and the change is gone.

The distractor this generates

A question shows a loop that doubles every element with s = s * 2; and then prints the array. Three of the four options are doubled arrays. The answer is the original array, unchanged.

4.1 To Write Into an Array, You Need the Index

for (int i = 0; i < seeing.length; i++)
{
   seeing[i] = seeing[i] * 2;   // this really does modify the array
}

The left-hand side is seeing[i] — the slot itself, not a copy of it. That is the difference, and it is the reason 4.4.A.4 exists as a separate statement.

5Arrays of Object References

Essential knowledge 4.4.A.5

When an array stores object references, the attributes can be modified by calling methods on the enhanced for loop variable. This does not change the object references stored in the array.

The rule has not changed — the loop variable is still a copy. What changed is what is being copied. Copying a reference gives a second arrow to the same object.

Telescope[] scopes = {new Telescope("Merz", 0),
                       new Telescope("Grubb", 0)};

for (Telescope t : scopes)
{
   t.addHours(3);   // DOES change the objects
}

Both telescopes now log three hours. The array still holds exactly the same two references — nothing about the array was touched. The method reached through the copied reference and changed the object at the other end of it.

for (Telescope t : scopes)
{
   t = new Telescope("Cooke", 0);   // changes NOTHING that survives
}

This is 4.4.A.4 again, unchanged. Assigning to t re-points the copy. The slot in the array still references the original object, and the new one is discarded at the end of the iteration.

The two-line rule for enhanced for loops

A dot changes the object. An equals sign changes nothing. t.addHours(3); reaches through the copy to the real object. t = … only re-points the copy, and the copy is thrown away when the iteration ends.

6Every Enhanced for Can Be Rewritten

Essential knowledge 4.4.A.6

Code written using an enhanced for loop to traverse elements in an array can be rewritten using an indexed for loop or a while loop.

The rewrite is mechanical, and it goes one way freely:

Enhanced forIndexed for
for (double s : seeing)for (int i = 0; i < seeing.length; i++)
—double s = seeing[i]; as the first line of the body
The rest of the bodyUnchanged

6.1 Going the Other Way Is Not Always Possible

4.4.A.6 is written in one direction on purpose. An indexed loop can do three things an enhanced loop cannot:

NeedsEnhanced for
To know where an element isNo index exists to report
To write a value into the arrayOnly ever holds a copy
To visit part of the array, or backwards, or in pairsVisits every element, front to back, unless the loop exits early
Choosing between them

If the body only reads each element, the enhanced form is shorter and cannot go out of bounds. The moment the code needs a position, a write, or anything other than every-element-in-order, it needs an index.

7How This Is Assessed

ShapeWhat is really being tested
An enhanced loop that assigns to its variable, then the array is printed4.4.A.4 — the array is unchanged
An enhanced loop over objects calling a setter, then a field is printed4.4.A.5 — the objects did change
An indexed loop with <=The exception, thrown on the pass after the last element
“Rewrite this enhanced loop”4.4.A.6 — and remembering the hidden assignment line
A loop that must report which element it foundRecognizing that only the indexed form can

8Check Yourself

After for (double s : seeing) { s = s + 1; }, what does the array hold?

Response

Exactly what it held before. s is a copy of each element; adding to it changes the copy, and the copy is replaced on the next iteration. Writing into the array needs seeing[i] = ….

After for (Telescope t : scopes) { t.addHours(3); }, what has changed?

Response

Every Telescope object has three more hours logged. The array itself is untouched — it holds the same references it always did. The copy was a copy of the reference, so the method reached the original object.

Why does i <= arr.length throw only at the very end?

Response

Because every earlier index is valid. The loop runs correctly through 0 to length − 1, then takes one more pass at length, which does not exist. All the expected output appears before the exception, which is why the fault looks like it is somewhere after the loop.

Which of these needs an indexed loop: printing every element · reporting the position of the largest element · adding one to every element?

Response

The last two. Reporting a position needs an index, and writing into the array needs the slot rather than a copy. Printing every element is exactly what the enhanced form is for.

9Summary

StatementWhat to remember
4.4.A.1A traversal is a loop over all or an ordered sequence of elements
4.4.A.2Indexed for and while reach elements through an index
4.4.A.3The enhanced for variable is assigned a copy of each element
4.4.A.4Assigning to that variable never changes the array
4.4.A.5For object arrays, a method call through it does change the object
4.4.A.6Any enhanced loop can be rewritten as indexed or while; the reverse is not always true
The ruleA dot changes the object; an equals sign changes nothing
The one sentence

The enhanced for loop hands you a copy of each element, which is why it can never write into an array and why it can still change every object an array of references points at.