← Skill tree CS Skill Tree 0 CSCD210

The Enhanced for (for-each) and Its Limits

Textbook: BJP (Reges and Stepp)

Where you are: Week 0 review > The enhanced for (for-each)

Try This First

You want to double every value in an int[] array. Decide whether a for-each loop can do it before reading on.

Reveal

No. A for-each copies each element into a loop variable; assigning to that variable does not change the array slot. Changing slots needs a traditional for with an index.

Before You Start

Check each box you can do from memory. A box you cannot check yet is not a problem; it points you to a quick refresher, not a grade.

See Loops: for, while, and do-while if any of the above felt uncertain.

Not sure? Take the 60-second self-check.
  1. How many times does a while loop run its body? As long as its condition stays true, and zero times if the condition is false at the start.
  2. What three parts sit in a traditional for header? The initializer, the condition, and the update.

What You Need To Walk In With

Walk into the next class able to state these:

You should be able to: write a for-each that sums or prints an array, and name a case where it must become a traditional for.

How It Works

The enhanced for visits every element of an array or Iterable:

int[] xs = {10, 20, 30};
for (int v : xs) {
    System.out.println(v);   // prints 10, 20, 30
}

Read the colon as “in”: for each int v in xs. There is no index variable, no condition, and no update clause. The loop variable holds a copy of each element.

Three conditions must all hold to use a for-each:

  1. You visit every element in forward order.
  2. The body does not need the index.
  3. The body does not change the array’s slots.

If any condition fails, use a traditional for:

// Reading every element: for-each fits
int sum = 0;
for (int v : xs) { sum = sum + v; }

// Needs the index: traditional for
for (int i = 0; i < xs.length; i++) {
    System.out.println("index " + i + ": " + xs[i]);
}

// Changing slots: traditional for
for (int i = 0; i < xs.length; i++) {
    xs[i] = xs[i] * 2;
}

The enhanced for works on every collection that is Iterable, including ArrayList, LinkedList, and TreeSet. That single fact is the entry point into the iterator and collection patterns of the next course.

Worked Example: Predict, Then Check

int[] xs = {3, 5, 7};
int total = 0;
for (int v : xs) {
    total = total + v;
}
System.out.println(total);

Predict the output before reading on.

Reveal

15. The loop reads 3, then 5, then 7 into v and adds each to total, ending at 3 + 5 + 7 = 15. Reading every element in order is exactly what for-each is for.

A Common Mistake

A common belief is that assigning to the for-each loop variable changes the array. It does not: the loop variable is a copy of the element. Writing v = v * 2; inside a for-each doubles the copy and leaves the array untouched. To change slots, index them with a traditional for. (Source: BJP (Reges and Stepp), Ch 7; JLS 25, §14.14.2.)

Go Deeper (optional)

For the curious: the compiler turns a for-each over an array into an ordinary indexed for, and a for-each over an Iterable into calls on a hidden iterator (hasNext and next). The index or the iterator exists; the enhanced for just hides it. Building your own iterator so a class supports for-each is a core topic of the data-structures course.

Check Yourself

Close the notes and answer each one from memory, then reveal it. Pulling an idea back from memory is one of the strongest ways to make it stick.

Check your understanding

To double every value in an int[] array, can you use a for-each loop?

Tier 2 · JLS 25, 14.14.2

What does the for-each loop variable give you on each pass?

Tier 1 · BJP (Reges and Stepp), Ch 7

int[] xs={3,5,7}; int total=0; for(int v: xs){ total=total+v; } print(total). What prints?

Tier 1 · BJP (Reges and Stepp), Ch 7

Which of these supports a for-each loop?

Tier 2 · BJP (Reges and Stepp), Ch 7