Introduction
The enhanced for loop helps you go through all items in a list or array easily without using a counter.
The enhanced for loop helps you go through all items in a list or array easily without using a counter.
for (type item : collection) { // use item here }
The type is the data type of each item in the collection.
The collection can be an array or any object that implements Iterable.
numbers.int[] numbers = {1, 2, 3}; for (int num : numbers) { System.out.println(num); }
fruits array.String[] fruits = {"apple", "banana", "cherry"}; for (String fruit : fruits) { System.out.println(fruit); }
List<String> colors = List.of("red", "green", "blue"); for (String color : colors) { System.out.println(color); }
This program uses an enhanced for loop to print a sentence for each pet in the array.
public class Main { public static void main(String[] args) { String[] pets = {"dog", "cat", "parrot"}; for (String pet : pets) { System.out.println("I have a " + pet); } } }
You cannot change the collection inside the enhanced for loop.
It is simpler and less error-prone than a regular for loop with an index.
The enhanced for loop is a simple way to go through all items in arrays or collections.
It avoids manual counting and makes code easier to read.
enhanced for loop in Java?nums?int[] numbers = {1, 2, 3};
int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println(sum);String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println(fruits);
}List<Integer> nums = List.of(5, 12, 7, 20, 10); int count = 0; // Which code correctly counts numbers > 10?
Pass the test and this pattern moves unknown