AP® Computer Science A · Unit 4 · Topic 4.4

The Enhanced for Loop and What It Cannot Do

The enhanced for loop copies each array element's value into a fresh variable every pass, so reassigning that variable never changes the original array — it can read elements but never write them back.

The enhanced for loop, written as for (int x : arr), exists to shorten code that just walks through every element and reads it. No index, no bounds checking, no arr[i] — just a clean handoff of each value in turn. That simplicity is also its limit: there's no index variable available, so you can't know an element's position, and you can't skip around or go backwards. It's built for one job — visiting every element in order to read it.

Under the hood, each pass copies the current element's value into the loop variable. That variable is brand new storage, disconnected from the array the moment the value is copied in. Assigning to it — x = x·2 — just overwrites that temporary copy. The array's actual slot, arr[i], never hears about it. This is why for (int x : arr) { x = x·2; } leaves arr completely untouched: every x is a throwaway copy, recreated fresh on the next pass and discarded after.

Object references change the picture slightly but not the rule. When arr holds Student objects, each pass still copies a value into the loop variable — but that value is a reference, an address pointing at a shared object. Reassigning the loop variable still does nothing to the array, same as before. But calling a mutator through that reference, like student.setGrade(95), reaches into the real shared object and changes it for good, because the copy and the original point at the same thing.

Key terms

Enhanced for loop
A loop form that visits every element of an array or collection in order without an explicit index.
Loop variable
The fresh local variable that receives a copy of each element's value on every pass of an enhanced for loop.
Pass by value
Java's rule that assigning or passing a variable copies its stored value, whether that value is a primitive or a reference.
Reference
An address pointing to where an object actually lives in memory, stored inside an object-type variable.
Mutator
A method that changes an object's internal state, such as setGrade, reached through any reference to that object.

Watch it explained

  1. How it worksHow does the enhanced for loop copy each element into a fresh variable every pass?
  2. Worked exampleTrace an enhanced for loop that tries to double each element and find why nothing changes.
  3. Common mistakeWhy doesn't assigning to the loop variable in an enhanced for loop update the array?
  4. Going furtherWhat changes when the array holds object references instead of ints?

Check yourself

Your turn1 of 2
for (int x : arr) { x = x·2; } is meant to double every element of arr. What actually happens to arr afterward?

End of topic.