English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about another form of for loop in Java, that is, the enhanced for loop or for-each loop.
In Java, when dealing with arrays and collections, we can use the enhanced form of the for loop. Also known as for-Each loop. This is because the loop will traverse each element of the array or collection.
To understand the for-Before using the each loop, make sure you understand:
Why prefer for-Instead of the for loop, let's look at the following example using the each loop.
In this example, it shows how to use the standard for loop to traverse the elements of an array.
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]); } } }
Output:
a e i o u
Now, we will use for-The each loop performs the same task.
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); } } }
Output:
a e i o u
Here, we can see that the output of the two programs is the same.
When we analyze these two programs carefully, we can notice that the for-The each loop is easier to write and makes our code more readable. This is why it is called the enhanced for loop.
Therefore, it is recommended to use the enhanced for loop as much as possible in the standard for loop.
Let us first look at the for-Syntax of the each loop:
for(data_type item : collections) { ... }
Here,
collection -The collection or array you need to traverse.
item -A single item in the collection.
Execute for each iteration-Each loop, which is for-How the each loop works in Java.
Iteration - Traverses each item in the given collection or array (collections)
Stores - Each item in the variable (item)
AndExecutes repeatedlyThe main statement inside the loop.
Let us illustrate this clearly with an example.
This program calculates the sum of all elements in 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); } }
Output:
Sum = 19
In the above program, for-The execution of the each loop is as follows:
Iteration | Value |
---|---|
1 | number = 3 When, sum = 0 + 3 = 3 |
2 | number = 4 When, sum = 3 + 4 = 7 |
3 | number = 5 When, sum = 7 + 5 = 12 |
4 | number = -5 When, sum = 12 + (-5) = 7 |
5 | When number = 0, sum = 7 + 0 = 7 |
6 | number = 12 When, sum = 7 + 12 = 19 |
You can see the for in each iteration.-Each loop
Traverse each element in the numbers array.
Store it in the number variable.
And execute the main body, and add the number to the variable sum, and finally get the total number (sum).