Java For-Each Loop

Naveen AnamaneniUpdated · 4 min read

When a ticket checker walks through a coach, they don't think "seat number 0, seat number 1, seat number 2". They just visit each passenger in turn. Java's for-each loop (officially the enhanced for loop) works the same way: it hands you every element of an array or a list, one at a time, with no counter to manage.

Visit Each Element

The loop variable takes each value in turn
Marks.java▶ Try it
public class Marks {
    public static void main(String[] args) {
        int[] marks = {78, 92, 86, 64};
        for (int mark : marks) {
            System.out.println("Mark: " + mark);
        }
    }
}
Output
Mark: 78
Mark: 92
Mark: 86
Mark: 64

Read line 4 as "for each int mark in marks". In each round, mark holds the next element, from first to last.

Totals and Searches

Cart.java▶ Try it
public class Cart {
    public static void main(String[] args) {
        String[] items = {"Rice", "Dal", "Oil"};
        int[] prices = {340, 165, 190};
        int total = 0;
        for (int price : prices) {
            total += price;
        }
        for (String item : items) {
            System.out.print(item + " ");
        }
        System.out.println();
        System.out.println("Total: Rs. " + total);
    }
}
Output
Rice Dal Oil
Total: Rs. 695

The first loop adds up the prices; the second prints each item name. Neither needs to know how many elements there are.

Try it yourself: add a fourth item and price. Do you need to change either loop?

For-Each vs Counting for

NeedUse
Read every element, in orderfor-each: shorter, no index mistakes
The position (index) of each elementCounting for
Change the elements of an arrayCounting for
Go backwards, or skip some positionsCounting for
Walk two arrays side by sideCounting for

Works on Lists Too

for-each works on arrays and on any collection, such as an ArrayList (covered with collections, later in the course):

Stops.java▶ Try it
import java.util.List;
 
public class Stops {
    public static void main(String[] args) {
        List<String> stops = List.of("Vijayawada", "Warangal", "Kazipet");
        int count = 0;
        for (String stop : stops) {
            count++;
            System.out.println(count + ". " + stop);
        }
    }
}
Output
1. Vijayawada
2. Warangal
3. Kazipet

When you need a number for each element, a small counter like count works without switching to a counting loop.

Common Mistakes

Expecting to change the array through the loop variable. It's a copy; see the warning above.

Removing items from a list inside a for-each. It throws ConcurrentModificationException. The collections lessons, later in the course, show the safe ways.

Using the wrong type. for (String s : marks) on an int[] doesn't compile.

Practice

  1. Easy: Print the largest value in {45, 82, 17, 93, 60} using a for-each loop.
  2. Harder: Count how many marks in an array are 35 or above (passes) and how many are below, using one for-each loop.

Quick check: for-each

4 questions
1In for (int mark : marks), what is mark in each round?
2Which task needs a counting for instead of for-each?
3Does for (int m : marks) { m = 0; } change the array?
4Can for-each loop over a List?

Key Takeaways

Was this tutorial helpful?

Lesson 58 of 482