Main Content

for and foreach in Java

Archive - Originally posted on "The Horse's Mouth" - 2010-04-22 23:43:52 - Graham Ellis

Java has had a "traditional" for loop from the beginning:
  for (int k=0; k<Allwords.size(); k++) {

That's three semicolon separated elements:
• initial setting
• test to see if loop should continue
• action to be taken before each re-test

So that when that's used in a loop such as this:
  for (int k=0; k     System.out.print(Allwords.get(k) );
    System.out.println(" " +k);
    }

you can handle each member of a collection (array, ArrayList, Vector, etc) in turn. But - if you don't actually need the position number (that's also known as the index - k in this example) - that's a considerable amount more syntax than you need.

From Java 1.5 (that's also know as Java 5), an alternative form of the for loop has been available which is synonymous with the foreach loop in languages such as PHP. Here's an example:
  for (Object beads: Allwords) {
    System.out.println(beads);
    }


In effect, that's a shorthand notation. There's an iterator that passes the reference for each object in the collection in turn into the beads variable, so that you can process each directly without the need to go via the variable k.

So the for-with-iterator is a great mechanism form processing each member of a collection where you're not concerned with the position number, nor the concept of "next" or "previous" records - but if position number is important, you'll want to stick with the traditional form or the loop.