Enhanced for-each loop in Java
Iterating arrays and Iterables; cannot modify the index.
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);
}Your turn
What prints?
var parts = List.of("home", "ana", "docs");
String path = "";
for (String p : parts) {
path = path + "/" + p;
}
System.out.println(path);/home/ana/docs/docs/ana/homehome/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}Did the prices double?
What prints?
int[] prices = {10, 20};
for (int p : prices) {
p = p * 2;
}
System.out.println(prices[0] + prices[1]);60301020
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 (int x : a) {
x = x * 2;
}Only copies change. The array is untouched.
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.
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 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
- Works on arrays and anything Iterable (List, Set...)
- Always walks forward through every element; no index available
- The loop variable holds a copy of each element's value
- Use an index loop when you need positions or want to replace elements
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);- abc
- c
- cba
- 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]);- 10 30
- 1 3
- 10 3
- 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.