The For-Loop: The For-Each Version of the For-Loop

For loop is the one of the basic control flow statement which is used to iterate and execute the same code again and again till the condition is matched. We already know the basic format of a for loop:
 for (initialization; test; update){
//code to execute
}
.

Introduction to “foreach” loop

In JDK5 this version was enhanced to produce a second form of for loop, i.e., the for-each loop. This loop is designed to run through a collection of objects, e.g. array, list, set etc in a sequential manner from the start to the end. Many languages such as c# implement the for-each style of the loop using the keyword ‘foreach‘ but in Java, the for-each loop can be implemented without the use of any new keyword. The syntax of the for-each loop is given below:

for(type itr_var : collection) {
    Statement block
}

We see that no new keyword is used in the for-each block and it looks very simple when compared to the traditional for loop. This is the reason why the for-each loop is also known as the enhanced for loop.  In the syntax, the type refers to the type of the collection objects, e.g. the type of the elements of the array. Itr_var refers to the iteration variable which is very much like the iteration variable used in the traditional for loop for running through the entire data. It extracts and stores one element at a time from the beginning to the end. The collection refers to the collection of objects or data which is being used, e.g. an array. Any other type of collection can be used with the for-each loop. And the statement block iterates through the entire collection from the beginning to the end until all the elements are exhausted. Here is a program which shows the use of the for-each loop:

/**
 * Program to print the average of 10 numbers stored in an array using the for-each loop.
 */
public class TestForEach {

    public static void main(String args[]) {

        int num[] = { 3, 6, 1, 4, 9, 7, 4, 6, 2, 8 }, sum = 0;

        // the for-each loop: integer type data with n as the iteration variable used to access the array num[]
        for (int n : num) {
            //we simply write n as n stores the current array element that is being accessed
            sum = sum + n;
        }

        System.out.println("The average of the numbers in the array is : " + (sum / 10));
    }
}

Output:-
The average of the numbers in the array is : 5

Use of ‘break/continue’ in the for-each loop

Now, we see that for-each loop runs from the start to the end but the question that arises here is that can we end the loop before we reach the end of the collection??

The answer is yes. We can simply use the break statement to exit the loop any moment as desired. The following program shows how to exit the loop before the end of the collection.

We can also use continue keyword in case we want to skip some values during the iteration. For detail understanding let’s understand through an example –

/**
 * Program to print the sum of 10 numbers stored in an array using the for-each loop.
 * The loop terminates if one of the elements is 7 and prints the obtained sum.
 */
public class ForEachBreak {

    public static void main(String args[]) {
        int num[] = { 3, 6, 1, 4, 9, 7, 4, 6, 2, 8 }, sum = 0;

        // the for-each loop: integer type data with n as the iteration variable used to access the array num[].
        for (int n : num) {
            //we simply write n as n stores the current array element that is being accessed
            sum = sum + n;
            if (n == 7) {
                break;
            }
        }
        System.out.println("The sum of the numbers in the array is : " + sum);
    }
}

Output:-
The sum of the numbers(till 7) in the array is : 30
The sum of the numbers(except 7) in the array is : 50

For-Each iteration variable is ‘read-only’

Another important thing to be noted about the for-each loop is that the iteration variable is ‘read-only’, i.e. any changes made to the iteration variable in the loop does not affect the value of the elements of the collection. Or we cannot change the value of the array elements by changing the value of the iteration variable. For example:

/**
 * Program to print the elements in the array before and after making changes to the iteration variable.
 */
public class ForEachItr {

    public static void main(String args[]) {
        int num[] = { 3, 6, 1, 4, 9, 7, 4, 6, 2, 8 };

        // the for-each loop: integer type data with n as the iteration variable used to access the array num[]
        // Original array elements
        System.out.println("The original array elements are : ");

        for (int n : num) {
            System.out.print(n + " ");
        }

        // Changes made to n
        System.out.println("\nArray elements after changes being made to n : ");

        for (int n : num) {
            System.out.print(n + " ");
            n += 2;
        }
    }
}

Output:-
The original array elements are : 
3 6 1 4 9 7 4 6 2 8
Array elements after changes being made to n : 
3 6 1 4 9 7 4 6 2 8

We see that the output remains the same. Hence, we can conclude that the changes made to the iteration variable have no effect on the collection elements.

Note: If the data contained is of Object type and some parameter value of the object is updated then it will reflect in the object whenever accessed again. It is because foreach loop does not clone the object and you have updated the value in the Object itself.


Using the For-Each Loop in Multi-dimensional Arrays

The for-each loop also works for multidimensional arrays. In this case, we have to work with the basic principle that a multidimensional array is actually an array of arrays; example a 2D array is just an array of multiple 1D arrays. The outer loop obtains an array for every iteration and the inner loop access the elements of the array. The following example shows this concept:

/**
 * Program to print the elements in a 2D array
 */
public class ForEachMultiDim {

    public static void main(String args[]) {

        int num[][] = { { 3, 6, 1 }, { 4, 9, 7 }, { 4, 6, 2 } };

        //the for-each loop: integer type data with n[] as the iteration variable used to access the array num[][]
        for (int n[] : num) {

            //The inner loop with iteration variable x used to access the multiple 1D arrays accessed by n[]
            for (int x : n) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}

Output:-
3 6 1
4 9 7
4 6 2

Applications of the For-Each Loop

An important advantage of the for-each loop over the traditional for loop is that in the latter we need to manually index the array with the iteration variable and assign the end of the loop condition and also update the iteration variable. All these three lines are combined to form a single line in the for-each loop and automate the process.

Due to its simplicity and efficiency, the for-each loop is found useful in many cases. A large number of algorithms follow the loop’s principle of sequential iteration from start to the end. Eg: calculating the sum or average, minimum and maximum, linear search, redundancy check, etc.

Hope this post helps you in your learning path and you like the tutorial. So, do come back for more.

Do ask for any queries in the comment box and provide your valuable feedback. Share and subscribe.

Keep Coding!! Happy Coding!! 🙂

Recommended -