For-Each Loop

There is a fourth kind of loop in Java that is handy for stepping through collections of elements, such as arrays. The syntax is:

for (type name : list) 
{

}

Here, type is the type of elements in the list, name is a variable that will step through each element, and list is the name of the list or array of elements.

Example with single-dimensional array

To see how the for-each loop works, suppose we have declared this array:

double[] vals;

Further suppose that we have allocated space for the array and filled it with initial values. Here is how we could use a for-each loop to print every element in the array:

for (double num : vals) 
{
    System.out.println(num);
}

This loop will step through the array starting and index 0. Each time, num will be given the value of the next element in the array.

Restrictions of for-each loop

One caveat to using a for-each loop is that you CANNOT use it to change any values in the array. For example, we might try to set every value in the vals array back to zero:

for (double num : vals) 
{
    //Won’t change array
    num = 0.0;
}

This code would compile, but it would not change the array. In that for-each loop, num is assigned the value of the first element in the array, then the second, etc. What the above loop does is change the current value of num – not the current array spot. If you want to change elements in an array, use one of the other types of loops.

Example with two-dimensional array

We can also use a for-each loop to step through every element in a two-dimensional array. Just like with other loops, we need an outer loop to step through the rows, and an inner loop to step through the elements on that row. For example:

int count = 0;
int[][] arr = new int[4][5];

//use standard for loops to initialize the array
for (int i = 0; i < 4; i++) 
{
    for (int j = 0; j < 5; j++) 
    {
        arr[i][j] = count;
        count++;
    }
}

/*Now the array looks like:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
*/

//now use a for-each loop to print each element
//elements printed will be 0, 1, 2, etc. ("read" arr like a book)
for (int[] val : arr) 
{
    for (int x : val) 
    {
        System.out.println(x);
    }
}