The Java for-each loop is a simple and easy way to go through elements of an array or collection one by one.
The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements.
The main advantage of the for-each loop is that it eliminates the possibility of common programming bugs, such as index-out-of-bound errors. It makes the code cleaner, shorter, and more readable. The loop is called a for-each loop because it processes each element one by one automatically
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.
However, it is recommended to use the Java for-each loop for traversing the elements of array and collection because it makes the code readable.
The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:), then array or collection.
The Java for-each loop traverses the array or collection until the last element. For each element, it stores the element in the variable and executes the body of the for-each loop.
The following are the steps:
Practice these examples to understand the concept of for each loop in Java.
In this example, the Java for-each loop goes through each element of the arr array one by one. During every iteration, the current value of the array is stored in the variable i, and System.out.println(i) prints that value. The loop continues automatically until all elements of the array are printed.
Output:
12 13 14 44
In this example, the Java for-each loop iterates through each element of the arr array. During every iteration, the current element is stored in the variable i and added to the total variable. After the loop finishes, the program prints the sum of all array elements.
Output:
Total: 83
This example demonstrates how the Java for-each loop is used to traverse an ArrayList and print each element one by one.
Output:
vimal sonoo ratan
We request you to subscribe our newsletter for upcoming updates.