dcsimg

How do I use the for-each construct?

John Zukowski

Any class that implements the Iterable interface can be used in a for-each statement: for (Datatype localvar : Iterable-instance). For instance, the following will print out each command-line argument sent to your program:

public class ForEach {
  public static void main(String args[]) {
    for (String entry: args) {
      System.out.println(entry);
    }
  }
}