The for-each loop
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)The for-each loop visits every element of an array, one by one, without an index: for (int m : marks). Read it as "for each m in marks".
How for-each works
To announce every batsman you need each name, not its position. A for-each loop hands you the elements one by one, first to last, with no index; read the : as "in".
Example 1 · Print every player
public class Team { public static void main(String[] args) { String[] team = {"Rohit", "Virat", "Shubman", "Rishabh"}; for (String name : team) { System.out.println("Batting: " + name); } }}Batting: Rohit Batting: Virat Batting: Shubman Batting: Rishabh
What this code does
- In each round,
nameholds the next element ofteam: first Rohit, then Virat, and so on. - There is no index, no
lengthand no condition to write, so there is no off-by-one mistake to make.
The variable's type must match the elements: for (int t : temps) over a double[] gives the compile error incompatible types: possible lossy conversion from double to int.
for-each or an index loop?
for-each is shorter and has no index to get wrong, but it can only read, from first to last. So ask what the job needs: the position, another order, or a change to the array?
Example 2 · Total of a shopping cart
public class CartTotal { public static void main(String[] args) { int[] prices = {120, 45, 300, 80}; int total = 0; for (int p : prices) { total += p; } System.out.println("Total: Rs. " + total); }}Total: Rs. 545
What this code does
totalstarts at 0 before the loop and each price is added to it, a running total as in Understanding loop flow (opens in a new tab).pis 120, then 45, 300 and 80; nothing in the job needs to know where each price sits.
Any of those three needs the index loop from Looping through an array (opens in a new tab). Only reading every element, like this total, is a job for for-each.
Classify
Which loop fits?
Tap a task, then tap the loop that fits it best.
for-each cannot change the array
You try to add 5 grace marks with for-each, and the marks stay the same. The loop variable gets a copy of each element, so changing it never reaches the box in the array.
Example 3 · for-each changes only a copy
public class GraceTry { public static void main(String[] args) { int[] marks = {40, 32, 55}; for (int m : marks) { m = m + 5; } System.out.println("With for-each: " + marks[1]); for (int i = 0; i < marks.length; i++) { marks[i] = marks[i] + 5; } System.out.println("With index loop: " + marks[1]); }}With for-each: 32 With index loop: 37
What this code does
- In the for-each loop,
mis a copy of each mark, so adding 5 to it leaves the array alone. - The index loop writes to
marks[i], the box itself, so the array really changes.
Next step
Check your understanding
8 quick questions