Java

Java For-Each Loop

  • Java
  • 5 mins read

Starting with JDK 5, the second form of for was defined that implements a “for-each” style loop. As you remember, contemporary language theory has included the for-each concept, and it has become a common feature that programmers have come to expect.

A for-each style loop is created to cycle through a collection of objects, such as an array, in a strictly sequential fashion, from start to end. Unlike some languages, such as C#, that execute a for-each loop by using the keyword foreach, Java adds the for-each capability by improving the for statement. The utility of this approach is that no new keyword is needed, and no preexisting code is broken. The for-each style of for is also mentioned as the enhanced for loop.

Java For-Each Loop Syntax

The standard form of the for-each version of the for is given here:

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

Here, type defines the type and itr-var specify the name of an iteration variable that will receive the elements from a collection, one at a time, from start to end. The collection being cycled through is defined by collection. With each iteration of the loop, the other element in the collection is retrieved and stored in itr-var. The loop repeats until all items in the collection have been received.

Since the iteration variable receives values from the collection, type must be the same or compatible with the elements stored in the collection. Therefore, when iterating over arrays, type must and should be compatible with the element type of the array.

For-Each Loop Examples

To understand the motive behind a for-each style loop, consider the type of for loop that it is designed to replace. The following fragment uses a traditional or conventional 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 += nums[i];

To calculate the sum, each element in nums is read, in order, from start to end. Hence, the entire array is read in a strictly sequential order. This is achieved by manually indexing the nums array by i, the loop control variable.

The for-each style for automates the preceding loop. Mainly, it eliminates the need to establish a loop counter, specify a starting and ending value, and manually index the array.  Instead, it automatically cycles within the entire array, obtaining one element at a time, in sequence, from start to end. For instance, here is the preceding fragment rewrote using a for-each version of the for:

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums) sum += x;

With every pass through the loop, x is automatically assigned a value equal to the next element in nums. Therefore, on the first iteration, x contains 1; on the second iteration, x holds 2; and so on. Not only is the syntax streamlined, but it also limits boundary errors.

Here is a complete program that explains the for-each version of the for just described:

// Use a for-each style for loop.
class ForEach {
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);
}
}
The output from the program is shown here:
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

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

Although the for-each for loop iterates, until every element in an array have been checked, it is likely to terminate the loop early by using a break statement. For instance, this program sums only the first five elements of nums:

// Use break with a for-each style for.
class ForEach2 {
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);
}
}
This is the output produced:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Summation of first five elements: 15

As it is apparent, the for loop stops after the fifth element have been reached. The break statement can also be used with Java’s other loops.

There is one essential point to understand about the for-each style loop. Its iteration variable is “read-only” as it links to the underlying array. An assignment to the iteration variable does not affect the underlying array. In other terms, you can’t change the contents of the array by providing the iteration variable a new value. For instance, consider this program:

// The for-each loop is essentially read-only.
class NoChange {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x: nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}

The first for loop increases the value of the iteration variable by a factor of 10. Nevertheless, this assignment does not affect the underlying array nums, as the second for loop illustrates. The output, shown here, proves this point:

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

See also: