🔀 Control Flow · Beginner

Enhanced for-each loop in Java

Iterating arrays and Iterables; cannot modify the index.

🧩 The mysteryYou loop over an array and multiply every element by 10. Afterwards the array is... completely unchanged. Who undid your work?

For each item in the box

for (int n : nums) reads as "for each int n in nums". It visits every element from first to last. It works on arrays and anything Iterable, like a List or Set. Shorter than an index loop, and it can't go out of bounds.

int[] nums = {3, 5, 7};
for (int n : nums) {
    System.out.println(n);
}
🔮 Predict it

Your turn

What prints?

var parts = List.of("home", "ana", "docs");
String path = "";
for (String p : parts) {
    path = path + "/" + p;
}
System.out.println(path);
  1. /home/ana/docs
  2. /docs/ana/home
  3. home/ana/docs/
Show the answer

Elements arrive in list order: home, ana, docs. Each pass appends "/" plus the element, building the path left to right.

The loop variable is a copy

Each pass, the loop variable receives a copy of the element's value. It's a separate variable, not the array slot. Assigning to it changes only the copy. Also, there's no index: for-each hands you values, never positions.

int[] a = {1, 2, 3};
for (int x : a) {
    x = x * 10; // changes only x
}
// a is still {1, 2, 3}
🔮 Predict it

Did the prices double?

What prints?

int[] prices = {10, 20};
for (int p : prices) {
    p = p * 2;
}
System.out.println(prices[0] + prices[1]);
  1. 60
  2. 30
  3. 1020
Show the answer

30. p held copies of 10 and 20; doubling the copies left the array untouched. (And it's 30, not "1020": adding two ints gives a number.)

Replacing every element

✗ for-each
for (int x : a) {
    x = x * 2;
}

Only copies change. The array is untouched.

✓ Index loop
for (int i = 0; i < a.length; i++) {
    a[i] = a[i] * 2;
}

Writing to a[i] needs the index. Use for-each to read, an index loop to replace or to know positions.

⚠️ The trap

Not everything is iterable

for-each needs an array or an Iterable. A String is neither, so looping over it directly is a compile error. Convert it first with toCharArray().

String word = "hi";
for (char c : word) { }   // compile error
for (char c : word.toCharArray()) {
    System.out.print(c);  // fine: hi
}
💼 In the real world

In real projects

for-each is the everyday way Java code reads collections: every order, every user, every line of a file. One gotcha you'll meet later: removing items from a List while for-each-ing over it usually throws ConcurrentModificationException.

Key takeaways

  1. Works on arrays and anything Iterable (List, Set...)
  2. Always walks forward through every element; no index available
  3. The loop variable holds a copy of each element's value
  4. Use an index loop when you need positions or want to replace elements
🤯 Did you know?

for-each arrived in Java 5 (2004). Over an array, the compiler turns it into a plain index loop; over a List or Set, it uses an Iterator behind the scenes.

Practice questions

What does this print?

String total = "";
for (String w : List.of("a", "b", "c")) {
    total = w + total;
}
System.out.println(total);
  1. abc
  2. c
  3. cba
  4. a
Check your answer

cba. Elements arrive in list order a, b, c, but each one is put in front of total: "a", "ba", "cba".

What does this print?

int[] a = {1, 2, 3};
for (int x : a) {
    x = x * 10;
}
System.out.println(a[0] + " " + a[2]);
  1. 10 30
  2. 1 3
  3. 10 3
  4. Compile error
Check your answer

1 3. x is a separate variable that receives a copy of each element. Changing x never touches the array slots.

Next: two tiny words that bend loops. One escapes, one skips, and one of them was blamed for a nationwide phone outage.