Java for-each Loop

The enhanced for-each loop, also known as the for-each loop, was introduced in Java 5 as a simplified way to iterate over arrays or collections. It is a concise and readable way to loop through the elements of an array or collection without having to worry about the index or the size of the array or collection.

Here’s the syntax for a for-each loop in Java:

for (type variable : array/collection) {
    // code to be executed
}

The loop starts with the keyword for, followed by parentheses containing three elements separated by semicolons. The first element is the type of the variable that will hold the value of each element in the array or collection. The second element is the name of the variable, followed by a colon. The third element is the array or collection that you want to loop through.

Here’s an example of using a for-each loop in Java to print the elements of an array:

int[] numbers = {1, 2, 3, 4, 5};

for (int number : numbers) {
    System.out.println(number);
}

In this example, the loop iterates over each element in the numbers array and prints its value to the console.

You can also use a for-each loop to iterate over a collection, such as an ArrayList:

import java.util.ArrayList;

public class ForEachExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        for (String name : names) {
            System.out.println(name);
        }
    }
}

In this example, the loop iterates over each element in the names ArrayList and prints its value to the console.

One important thing to note about the for-each loop is that it is read-only. You cannot modify the elements of the array or collection inside the loop. If you need to modify the elements, you should use a regular for loop instead.

Follow us on social media
Follow Author