Using For-Each Loop in Java

The enhanced for loop in Java, also popularly referred to as the for-each loop, provides a more concise way to navigate through arrays or collections. This loop eliminates the necessity to manually handle indices or iterators, making the code more readable and less prone to errors. Instead of the traditional approach, the enhanced for loop gives direct access to every individual item within an array or collection during each iteration. This iteration mechanism designates a placeholder variable that represents the active item. Following this variable is a colon ":", which is then succeeded by the specific array or collection being iterated. This method allows Java developers to achieve efficient traversal with reduced code complexity. In this Java For-Each example, we created an array and iterated through each element through a For-Each loop. Click Execute to run the Java For-Each Example online and see the result.
Using For-Each Loop in Java Execute
import java.util.ArrayList;
import java.util.List;

public class ForEachDemo {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();

        for (String fruit : fruits) {
Updated: Viewed: 39 times