We have already learned about variations of for loop. There is one more variation for-each loop. for-each loop is used only for arrays and collections (A collection is a container that has multiple elements into one single unit and is used to store, retrieve, manipulate and communicate data). That's why I introduce this after introducing arrays. for-each loop is also called enhanced for loop and was introduced in Java1.5 (JDK 5).
NOTE: Collections are a set of classes that implement various data structures like lists, vectors, sets and maps. We will discuss about other kind of collections later in future posts.
The for-each loop enables the java program to traverse through the array elements sequentially without using the index variable. You also don't need to use array's length property. The general form for for-each loop is:
for(type variable: array) { }
Here type is data type same as or compatible to the array's data type, variable is an iteration variable which recieves the value of array element. With each iteration of the loop, the next element is passed to the variable. The loop repeats till the end of the array. Let's take last post arrays example once again and try to convert for loop into for-each loop.
for(int i = 0; i < nums.length; i++) { System.out.println("nums[" + i + "]:" + nums[i]); }
Here, we replace the simple for loop with enhanced for loop (for-each loop) -
for(int num: nums) { System.out.println(num); }
And the result is:
11
3
7
8
20
16
As the output shows, the for-each loop automatically cycles through an array in the sequence ordering from lowest index to the highest index. The for-each loop is useful when you need to examine whole array from start to finish like computing the sum of all the values or searching for a value etc. Let's write a program to sum of all the elements in an integer array.
Class ArrTest (ArrTest.java)
public class ArrTest { public static void main(String args[]) { int nums[] = {11, 3, 7, 8, 20, 16}; int sum = 0; for(int num: nums) { sum = sum + num; } System.out.println("Sum is " + sum); } }
Here is the output
Sum is 65
Although for-each loop is run from "start to end", it can be stopped in between using the break statement we discussed earlier. And one more important point is to be noted, as we are not using index to access the element of an array, we can not change the value of contents of the array in for-each loop, as you can do with traditional for loop.