Last Updated: 22 March, 2023
For traversing an array or Collection class, Java has introduced another form of the for loop in the Java 5 version that is known as the for-each loop. The for-each loop is a convenient way to iterate over elements in an array or collection, and it can make our code more readable and concise.
The for-each loop is also known as an "enhanced for-loop."
The syntax of the for-each loop is as follows:
Writing a for-each loop is very simple in comparison to other Java loops such as the for loop, while loop, or do-while loop. In the for-each loop, we don't have to initialize a loop counter or index variable; we declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array or Collection classes.
Example 1: Traversing an int array using for-each Loop
In the above code, the for-each loop iterates over each element in the "num_Array" array, and the value of each element is stored in the "number" variable. The loop then prints out each number to the console.
Output
Printing Numbers:
75 50 30 68 84
Example 2: Traversing a string array using for-each Loop
In the above code, the for-each loop iterates over each element in the "country_Array" array, and the value of each element is stored in the "country" variable. The loop then prints out each number to the console.
Output
Printing Country Name:
India
Japan
Sri Lanka
Nepal
Bangladesh
Example 3: Traversing a char array using for-each Loop
In the above code, the for-each loop iterates over each element in the "vowels" array, and the value of each element is stored in the "item" variable. The loop then prints out each number to the console.
Output
a
e
i
o
u
Example 4: Traversing a Collection using for-each Loop
In the above code, the for-each loop iterates over each element in the ArrayList, and the value of each element is stored in the "num" variable. The loop then prints out each number to the console and also adding each element and storing in totalSum variable.
Output
1000
2000
3000
4000
5000
Total Sum of List: 15000
While the Java for-each loop is a powerful feature that simplifies the process of iterating over arrays and collections, it does have some disadvantages that we should be aware of:
Despite these disadvantages, the for-each loop is still a powerful feature that can simplify the code and make it easier to read and understand.
That's all guys, hope this Java article is helpful for you.
Happy Learning.
feedback@javabytechie.com