Java For-Each Loop
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
public class Marks {
public static void main(String[] args) {
int[] marks = {78, 92, 86, 64};
for (int mark : marks) {
System.out.println("Mark: " + mark);
}
}
}Mark: 78
Mark: 92
Mark: 86
Mark: 64Read line 4 as "for each int mark in marks". In each round, mark holds the next element, from first to last.
Totals and Searches
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);
}
}Rice Dal Oil
Total: Rs. 695The 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
| Need | Use |
|---|---|
| Read every element, in order | for-each: shorter, no index mistakes |
| The position (index) of each element | Counting for |
| Change the elements of an array | Counting for |
| Go backwards, or skip some positions | Counting for |
| Walk two arrays side by side | Counting 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):
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);
}
}
}1. Vijayawada
2. Warangal
3. KazipetWhen 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
- Easy: Print the largest value in
{45, 82, 17, 93, 60}using a for-each loop. - Harder: Count how many marks in an array are 35 or above (passes) and how many are below, using one for-each loop.
Key Takeaways
Was this tutorial helpful?