Java for each Loop Example

Java for-each Loop Example demonstrates the usage of the for-each loop in Java with an example.

The For-Each Version of the for Loop

Beginning with JDK 5, the second form of for was defined that implements a “for-each” style loop. Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.

Syntax

for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end.
Here is an entire program that demonstrates the for-each version:
package net.javaguides.corejava.controlstatements.loops;

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

for-each Loop with Break

It is possible to terminate the loop early by using a break statement. For example, this program sums only the first five elements of nums:
package net.javaguides.corejava.controlstatements.loops;

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

Reference


Comments