The "foreach" Loop
Home ] Up ] The Java Statements ] Differences from C/C++ ] [ The "foreach" Loop ]

 

 

Java 5.0 added a very useful, new version of a for loop:  a "foreach" loop, which is also present in a number of other languages.  Java calls this new version an "enhanced for loop".

The "foreach" loop allows you to iterate through a collection of objects in a way that is much simpler than with a normal for loop.  

For the moment, we have only encountered one kind of collection: an array.  Later, we'll see how the "foreach" loop may be used with other kinds of collections.

Pre-Java 5

First, let's look at how we typically would have done this prior to Java 5.0:

package examples;

public class ForEachTest
{
  public static void main(String[] args)
  {
    String[] herbs = { "Basil", "Sage", "Rosemary", "Oregano" };
    for (int i = 0; i < herbs.length; i++)
    {
      String herb = herbs[i];
      System.out.println(herb);
    }
  }
}

which outputs:

Basil
Sage
Rosemary
Oregano

This form of a for loop uses a very standard Java idiom (it's also a standard idiom for C/C++ and other related languages) for iterating through the elements of an array.  Note how picky you have to be with the termination condition:

i < herbs.length

"Off by one" errors (also known as "fencepost" errors) are very common, even for experienced Java programmers.

Post-Java 5

Now, let's see how the "foreach" loop makes this much simpler (and safer!):

package examples;

public class ForEachTest
{
  public static void main(String[] args)
  {
    String[] herbs = { "Basil", "Sage", "Rosemary", "Oregano" };
    for (String herb: herbs)
    {
      System.out.println(herb);
    }
  }
}

which outputs exactly the same thing as the former example.

Notice how much simpler this version is!  Not only does it save several lines of code, it also eliminates the error-prone termination condition of the conventional for loop construct.

The compiler is doing more work for you!

 

This page was last modified on 02 October, 2007