Tuesday, August 22, 2006

Using the for loop with a colon?

I've gone through the famous Eckel book on "Thinking in Java" and could not find the examples I've seen in various code, using a for loop with : instead of commas.

Here is an example of one:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
While writing this entry, I found a site which gives some direction on this, but still I am not totally tracking. Looking for a better description.

This format of the "for" loop is generally called the "enhanced for loop" and is used with arrays and collections.

Enhanced For
The Enhanced For Loop

Looks like this was only released with JDK 5.0. No wonder I couldn't find it in my outdated reference books...

2 comments:

nicholas said...

http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html

Anonymous said...
This comment has been removed by a blog administrator.