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.
- Traversing an array uses repetition to access all or an ordered sequence of elements.
- Indexed
forandwhileloops reach elements using their indices. - An array of length 5 has indices 0 to 4;
i <= 5tries index 5 and throwsArrayIndexOutOfBoundsException. - 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};
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:
| Form | Gives you | Can write into the array? |
|---|---|---|
Indexed for | The index, and the element through it | Yes |
while | The same, with the counter written out separately | Yes |
Enhanced for | A copy of each element, and no index | No |
2The Indexed for Loop
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:
| Part | Written | Getting it wrong |
|---|---|---|
| Start | int i = 0 | Starting at 1 silently skips the first element |
| Condition | i < seeing.length | <= runs one past the end and throws |
| Update | i++ | Forgetting it is an infinite loop |
< 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
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);
}
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
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.
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
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.
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
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 for | Indexed 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 body | Unchanged |
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:
| Needs | Enhanced for |
|---|---|
| To know where an element is | No index exists to report |
| To write a value into the array | Only ever holds a copy |
| To visit part of the array, or backwards, or in pairs | Visits every element, front to back, unless the loop exits early |
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
| Shape | What is really being tested |
|---|---|
| An enhanced loop that assigns to its variable, then the array is printed | 4.4.A.4 — the array is unchanged |
| An enhanced loop over objects calling a setter, then a field is printed | 4.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 found | Recognizing that only the indexed form can |
8Check Yourself
After for (double s : seeing) { s = s + 1; },
what does the array hold?
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?
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?
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?
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
| Statement | What to remember |
|---|---|
| 4.4.A.1 | A traversal is a loop over all or an ordered sequence of elements |
| 4.4.A.2 | Indexed for and while reach elements through an index |
| 4.4.A.3 | The enhanced for variable is assigned a copy of each element |
| 4.4.A.4 | Assigning to that variable never changes the array |
| 4.4.A.5 | For object arrays, a method call through it does change the object |
| 4.4.A.6 | Any enhanced loop can be rewritten as indexed or while; the reverse is not always true |
| The rule | A dot changes the object; an equals sign changes nothing |
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.