4.6 The Enhanced for Loop

The Enhanced for Loop in Java

Unit 4: Loops and Collections of Actors · Lesson 4.6 · about 25 minutes · no coding experience needed

Half the loops you write only want to visit everything once and do not care where anything sits. For those, there is a shorter form that removes the whole class of off-by-one mistakes by removing the index entirely.

What you will be able to do

  • Write an enhanced for loop over a list
  • Choose between an enhanced for and an index loop
  • Name the two situations where the enhanced for cannot be used

Words you will need

Enhanced for
In plain words For each thing in this collection, do something.
More precisely A loop over an Iterable that binds each element to a variable in turn.

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 with its parts labeled: the type, the variable name, the colon, and the collection.

    for (Enemy e : getObjects(Enemy.class))
    {
        e.turn(180);
    }

    Read the colon as "in": for each Enemy e in this collection.

    `Enemy` is the type of thing coming out. `e` is the name you give each one as it comes. `:` is "in". After it is the collection.

    No counter, no condition, no update. There is no index to get wrong.

  2. Step 2

    On your screen The enhanced for and the index loop side by side, doing the same job.

    // Enhanced for
    for (Enemy e : enemies) { e.turn(180); }
    
    // Index loop, same result
    for (int i = 0; i < enemies.size(); i++)
    {
        enemies.get(i).turn(180);
    }

    Same job. The enhanced version is shorter and, more importantly, cannot go off the end, because there is no end to get wrong.

    When you do not need to know WHERE something is, prefer it.

  3. Step 3

    On your screen A situation requiring the index, with the position used in the loop body.

    // Needs the index, so an enhanced for cannot do it.
    for (int i = 0; i < enemies.size(); i++)
    {
        enemies.get(i).setLocation(i * 2, 0);
    }

    And here is when you cannot use it. This spaces the enemies out using their POSITION in the list, so the index is part of the job.

    An enhanced for hands you the item and nothing else. No item knows where it sits.

    The other case is removal: you still cannot remove from a collection while looping over it, and the enhanced form does not change that.

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 The enhanced for is faster.

What is actually true It is shorter and safer to write. Speed is not the point.

Why it matters Choosing on imagined performance rather than on whether you need the index.

Common wrong idea You can find out the index inside an enhanced for.

What is actually true You cannot. If you need it, use an index loop.

Why it matters Students add a manual counter, which works but throws away the reason to use it.

Common wrong idea An enhanced for makes removal safe.

What is actually true It does not. Removing during iteration still throws.

Why it matters A very tempting wrong conclusion, since the loop looks so much simpler.

Common wrong idea The colon means "to", as in a range.

What is actually true It means "in". For each e IN this collection.

Why it matters Reading it as a range makes the whole line incomprehensible.

Check your understanding

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

  1. 1. How is `for (Coin c : coins)` read aloud?

  2. 2. Which job CANNOT be done with an enhanced for?

  3. 3. What is the main advantage of the enhanced for?

  4. 4. Can you remove actors from the world inside an enhanced for over its list?

Fill in the code

Turn every coin in the world through a quarter circle, using the shorter loop form.

for (Coin c  getObjects(Coin.class))
{
    .turn(90);
}
Stuck? Open a hint for each blank
  • Blank 1: The single character that means "in".
  • Blank 2: The name given to each coin as it comes out of the collection.

Lesson quiz

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

  1. 1. In `for (Enemy e : enemies)`, what is e?

  2. 2. You need to know whether an item is the first in the list. Which loop?

  3. 3. The enhanced for is preferred when:

  4. 4. Compared with an index loop, the enhanced for is:

The short version

  • Read the colon as "in": for each Enemy e in enemies.
  • No index means no off-by-one.
  • Use an index loop when the position is part of the job.
  • It does NOT make removal during iteration safe.

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]