Java Five-Oh #1: For/In

Java 1.5, sometimes referred to as Java 5 or as I like to call it Java five-oooh, has been out for a while now and yet I recently got an email from a old college mate who emailed me immediately after he saw the new printf method in action in some sample code. So for my benefit, as well as his and maybe even yours, I am going to go break down over several entries some sample code detailing the new features in Java 1.5.

One Java 1.5 feature that I use most is probably the new foreach, for/in, statement. The new for/in construct is basically a new for loop that provides a shortcut for iterating over collections such as lists and arrays. The new for/in statement provides a shortcut for working with lists; you don’t have to declare iterators or integer indices. Here is the new foreach construct in action:

List l = ...
for(Object o : l) {
   System.out.println(o);
}

I’ve already written about generics in Java 1.5 and how to use the new for/in loop in conjunction with generics in Generic Java.