5.4 Enhanced for over an Array

The Enhanced for Loop over a Java Array

Unit 5: Arrays · Lesson 5.4 · about 20 minutes · no coding experience needed

You met this loop over lists in 4.6. It works on arrays too, with one extra limitation that catches people because it fails silently rather than loudly.

What you will be able to do

  • Write an enhanced for over an array
  • Explain why assigning to the loop variable changes nothing
  • Choose between the two loop forms

Words you will need

Copy
In plain words The loop variable holds a copy of the value, not the slot itself.
More precisely The loop variable is assigned the element value on each iteration.

Build it step by step

Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.

  1. Step 1

    On your screen An enhanced for loop over an int array with each value read in turn.

    int[] lanes = {3, 7, 2, 9};
    for (int lane : lanes)
    {
        addObject(new Coin(), lane, 0);
    }

    Same form as 4.6. Read the colon as "in": for each int lane in lanes.

    No index, no length, no condition. Nothing to get off by one.

    When you only need the VALUES, this is the better loop.

  2. Step 2

    On your screen An attempt to assign to the loop variable, with the array unchanged afterward.

    // Does NOT change the array.
    for (int lane : lanes)
    {
        lane = lane * 2;
    }
    // lanes is still {3, 7, 2, 9}

    This is the limitation, and it is worth meeting deliberately because it fails in silence.

    `lane` is a COPY of the value, not the slot. Doubling the copy changes the copy. The array is untouched, there is no error, and nothing tells you.

    To write into the array you need the index: `for (int i = 0; i < lanes.length; i++) { lanes[i] = lanes[i] * 2; }`

  3. Step 3

    On your screen A decision table for choosing between the two loop forms.

    The choice, in one line each:

    Reading values only: enhanced for. Shorter and safer. Need the position: index loop. Need to WRITE into the array: index loop.

    Unit 6 uses index loops almost exclusively, because a tile map is entirely about position.

Mistakes almost everyone makes here

These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.

Common wrong idea Assigning to the loop variable updates the array.

What is actually true It updates a copy. The array is unchanged and nothing warns you.

Why it matters A silent no-op is far worse than an error, and this one looks completely reasonable.

Common wrong idea The enhanced for can give you the index if you ask.

What is actually true It cannot. Use an index loop.

Why it matters Adding a manual counter works but discards the reason for using it.

Common wrong idea The enhanced for is always better because it is shorter.

What is actually true It is better only when you need values alone.

Why it matters Half of Unit 6 needs positions, so this would be the wrong habit to form.

Check your understanding

Answer these before moving on. They are graded instantly and you can retry.

  1. 1. What does `for (int v : a)` give you each pass?

  2. 2. `for (int v : a) { v = 0; }` What happens to a?

  3. 3. You need to double every value IN the array. Which loop?

  4. 4. You just want to add up every value. Which loop is cleaner?

Fill in the code

Add up every value in an array called scores, using the shorter loop form.

int total = ;
for (int s  scores)
{
    total = total + ;
}
Stuck? Open a hint for each blank
  • Blank 1: Nothing has been added yet.
  • Blank 2: One character meaning "in".
  • Blank 3: The name given to each value as it comes out.

Lesson quiz

This one counts toward your progress. Take it when the section above makes sense.

  1. 1. The enhanced for over an array gives you:

  2. 2. Why can an enhanced for not change the array?

  3. 3. Which job needs an index loop?

  4. 4. The main advantage of the enhanced for is:

The short version

  • `for (int v : a)` visits every value, with no index.
  • The loop variable is a COPY. Assigning to it changes nothing, silently.
  • Use an index loop to write into the array or to use positions.
  • Unit 6 is mostly index loops, because tile maps are about position.

If you get stuck

These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]