codescracker


java

Java For-each or Enhanced for Loop



« Previous Tutorial Next Tutorial »


Beginning with the JDK 5, a second form of the for loop was defined which implements a "for-each" style loop.

The for-each style of for loop is designed to cycle by a collection of objects, such as an array, in strictly sequential fashion, from the start to end.

Unlike some other computer languages like C#, that implements a for-each loop by using the foreach keyword, Java adds for-each capability by enhancing the for loop. The advantage of this approach is that there is no new keyword required, and also no pre-existing code is broken.

The for-each style of the for loop is also referred to as enhanced for loop.

Java for-each for Loop Syntax

The general form of for-each version of the for loop is shown below :

for(type itr-var: collection) statement-block

Here, type specifies the data type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from the beginning to end. The collection being cycled through is specified by collection. There are several types of collections that can be used with the for, but the only type used in this tutorial is the array.

With each iteration of the loop, the next elements in the collection is retrieved and stored in itr-var. The loop repeats before all the elements in the collection have been obtained.

Because the iteration variable gets values from the collection, type must be the same as (or compatible with) the elements stored in the collection. Therefore, when iterating over arrays, type must be compatible with the element type of the array.

To realize the motivation behind a for-each style loop, look at the type of the for loop that it is designed to replace. Here this code fragment uses a traditional for loop to compute the sum of the values in an array :

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

for(int i=0; i<10; i++)
{
	sum = sum + nums[i];
}

To calculate the sum each element present in nums is read from the start to finish. Therefore, the entire array is read purely in sequential order. This is achieved by manually indexing the nums array by the loop control variable i.

The for-each style for automates the previous loop. Specifically, it eliminates the need to establish a loop counter, specify the starting and the ending value, and manually index the array. Instead, it automatically cycles through the entire array, getting one element at a time, in sequence, from the beginning to end. For example, following is the preceding code fragment rewritten by using the for-each version of the for loop:

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

for(int x: nums)
{
	sum = sum + x;
}

With each pass through the loop, x is automatically given a value equal to the next element in the variable nums. Therefore, in the first iteration, x contains 1, in the second iteration, x holds 2, and so on. Not only is the syntax efficient, but it also prevents the boundary errors.

Java for-each for Loop Example

Following is an entire program that illustrates the for-each version of the for loop just described :

/* Java Program Example - Java for-each Loop
 * This program uses a for-each style for loop 
 */

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int sum = 0;
        
        // use the for-each style for loop to display and sum the values
        for(int x : nums)
        {
            System.out.println("Value is " + x);
            sum = sum + x;
        }
        
        System.out.println("\nSummation is " + sum);
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java for each loop

As the above output shows, the for-each style of the for loop automatically cycles through an array in sequence from the lowest index to highest.

Even though the for-each for loop iterates until all the elements in an array have been examined, it is also possible to terminate the loop early by using a break statement. For example, the following program sums only starting five elements of nums :

/* Java Program Example - Java for-each Loop
 * Use a break with a for-each style for */

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        int sum = 0;
        int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        
        // use for-each for loop to display and sum the values
        for(int x : nums)
        {
            System.out.println("Value is " + x);
            sum = sum + x;
            if(x == 5)     // stop the loop
                break;     // when 5 is obtained
        }
        
        System.out.println("Summation of first 5 elements is " + sum);
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java for each for loop

Here, the for loop stops after the fifth element has been obtained. The break statement can also be used with other loops. You will learn about break statement in separate chapter.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test