Nelz's Blog

Mah blogginess

Java 5 FOREACH Syntax

For those that don’t currently use the new Java 5 "foreach" syntax, you are missing out.

I got to a point today where I wanted to verify that the construct is doing the intelligent thing, so I wrote the following unit test:

@Test
public void forEachLoop() {
for (String str : doHeavyWeigthMethod()) {
System.out.println(str);
}
}
private List<String> doHeavyWeigthMethod() {
System.out.println("heavyMethod");
final List<String> results = new ArrayList<String>();
results.add("one");
results.add("two");
results.add("three");
return results;
}

I was psyched to see the output:

heavyMethod
one
two
three

Basically, this shows that the foreach construct only evaluates the collection once and caches the value to be used in each iteration.

However, the construct is not without some pitfalls. I would have expected the new construct to be programmed more defensively, but it is still susceptible to NullPointerException. Running the following throws the NPE:

@Test
public void forEachLoop() {
for (String str : doHeavyWeigthMethod()) {
System.out.println(str);
}
}
private List<String> doHeavyWeigthMethod() {
return null;
}

So, unless you know you are in control of the method you are calling in the expression part of the "foreach" construct, you still need to defensively check for null. And, we all know how much I love that, right?