Java For-Each Loop

The for-each loop in Java, also known as the enhanced for loop, is used to iterate over elements in arrays and collections. It provides a simpler and more readable way to traverse data structures.

Key Topics

1. Syntax

for (type variableName : arrayName) {
    // Code to be executed
}

2. Example with Arrays

public class ForEachExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        for (int number : numbers) {
            System.out.println("Number: " + number);
        }
    }
}

3. Example with Collections

import java.util.ArrayList;

public class ForEachCollection {
    public static void main(String[] args) {
        ArrayList fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

4. Limitations

The for-each loop does not provide access to the index of the current element and does not allow modification of the collection during iteration.

Key Takeaways

  • The for-each loop simplifies iteration over arrays and collections.
  • Improves code readability and reduces the chance of errors.
  • Not suitable when you need to modify the collection or know the index of elements.