Home Java Tutorial Java for-each Loop

Java for-each Loop

by Anup Maurya
36 minutes read

The for-each loop, also known as the enhanced for loop, was introduced in Java 5 as a simplified way to iterate over arrays and collections. It provides a concise and easy-to-read syntax for iterating through elements of an array or a collection without the need for an explicit index or iterator.

The syntax for the for-each loop is as follows:

for (datatype variable : array/collection) {
    // statements to be executed for each element
}

The datatype is the data type of the elements in the array or collection, and the variable is a new variable that is declared and used for each element in the array or collection. The array/collection is the name of the array or collection that is being iterated over.

Here is an example of using the for-each loop with an array

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

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

In this example, the for-each loop iterates over the numbers array, and for each element in the array, it assigns the element to the variable num. The statements inside the loop simply print out the value of num. The output of this program would be:

1
2
3
4
5

Here is an example of using the for-each loop to Iterate over a 2D array

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

for (int[] row : matrix) {
    for (int num : row) {
        System.out.print(num + " ");
    }
    System.out.println();
}

In this example, we have a 2D array called matrix. The outer for-each loop iterates over each row of the matrix, and the inner for-each loop iterates over each element of the row. The statements inside the inner loop simply print out the value of each element followed by a space. The statements inside the outer loop print a newline character after each row to create a matrix-like output. The output of this program would be:

1 2 
3 4 
5 6 

Here is an example of using the for-each loop with a collection:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Dave");

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

In this example, the for-each loop iterates over the names collection, and for each element in the collection, it assigns the element to the variable name. The statements inside the loop simply print out the value of name. The output of this program would be:

Alice
Bob
Charlie
Dave

One important thing to note is that the for-each loop is read-only, which means that you cannot modify the elements in the array or collection while iterating over them. If you need to modify the elements, you should use a regular for loop with an index or an iterator.

In conclusion, the for-each loop is a simple and powerful feature of Java that allows you to easily iterate over arrays and collections. It can make your code more concise and readable, and it is definitely worth using whenever possible.

related posts

Leave a Comment