Java for-each Loop (Enhanced for Loop)
Updated Jan 6, 2021 View by 1.4 K

In Java, there is another form of for loop (in addition to standard for loop) to work with arrays and collection, the enhanced for loop.
Java for-each Loop (Enhanced for Loop)
If you are working with arrays and collections, you can use alternative syntax of for
loop (enhanced form of for
loop) to iterate through items of arrays/collections. It is also referred as for-each loop because the loop iterates through each element of array/collection.
To learn about standard syntax of for
loop, arrays and collections, visit:
- Java for Loop
- Java arrays
- Java collections
Here’s an example to iterate through elements of an array using standard for loop:
class ForLoop { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; for (int i = 0; i < vowels.length; ++ i) { System.out.println(vowels[i]); } } }
You can perform the same task using for-each
loop as follows:
class AssignmentOperator { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // foreach loop for (char item: vowels) { System.out.println(item); } } }
The output of both programs will be same:
a e i o u
The use of enhanced for
loop is easier to write and makes your code more readable. Hence, it’s recommended over standard form whenever possible.
Syntax of for-each loop
Let’s first look at the syntax of for each loop:
for(data_type item : collection) { ... }
In the above syntax,
- collection is a collection or array variable which you have to loop through.
- item is a single item from the collection.
How for-each loop works?
Here’s how the enhanced for loop works. For each iteration, for-each loop
- iterates through each item in the given collection or array (collection),
- stores each item in a variable (item)
- and executes the body of the loop.
Let’s make it clear through an example.
Example: for-each loop
The program below calculates the sum of all elements of an integer array.
class EnhancedForLoop { public static void main(String[] args) { int[] numbers = {3, 4, 5, -5, 0, 12}; int sum = 0; for (int number: numbers) { sum += number; } System.out.println("Sum = " + sum); } }
When you run the program, the output will be:
Sum = 19
In the above program, the execution of foreach loop looks as:
Iteration | Value of number | Value of sum |
---|---|---|
1 | 3 | 3 |
2 | 4 | 7 |
3 | 5 | 12 |
4 | -5 | 7 |
5 | 0 | 7 |
6 | 12 | 19 |
You can see during each iteration, the foreach loop
- iterates through each element in the numbers variable
- stores it in the number variable
- and executes the body, i.e. adds number to sum