Skip to lesson

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".

Syntax
for (type name : array) {
body
}

Example 1 · Print every player

Team.javaJava
public class Team {    public static void main(String[] args) {        String[] team = {"Rohit", "Virat", "Shubman", "Rishabh"};        for (String name : team) {            System.out.println("Batting: " + name);        }    }}
Output
Batting: Rohit
Batting: Virat
Batting: Shubman
Batting: Rishabh

What this code does

  • In each round, name holds the next element of team: first Rohit, then Virat, and so on.
  • There is no index, no length and 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

CartTotal.javaJava
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);    }}
Output
Total: Rs. 545

What this code does

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.

for-each copies marks[1], which is 32, into m. m = m + 5 makes m 37, but the box marks[1] still holds 32: only the copy changed.

Example 3 · for-each changes only a copy

GraceTry.javaJava
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]);    }}
Output
With for-each: 32
With index loop: 37

What this code does

  • In the for-each loop, m is 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