Skip to main content

Pet peeve with the Java 1.5 enhanced for loop

Posted by inder on May 24, 2007 at 4:15 PM PDT

I love the enhanced for loop construct introduced in Java 1.5. It makes the code look clean, and saves us from dealing with iterators or array indices. But since it is essentially syntactic sugar, it does create iterators behind the scenes as necessary. This can result in insidious bugs since if the passed collection or the array is null, your for loop will throw a NullPointerException. Here is an example:

import java.util.List;

public class ForLoopTest {

  public static void main(String[] args) {

   List<String> items =  null;

   for (String item : items) {

     System.out.println("Item:" + item);




When this program is run, it will throw a null pointer exception.

I think it would have been better if the for loop did a null pointer check on the collection before trying to iterate over it. Granted, it will have a little bit of overhead, but I think the cost is justified because it is really common for people to not check for null values before invoking the for loop. I dont expect the semantics to get changed now because of backward compatibility concerns, so dont hold your breath expecting a change. But still, what do you think? Did the language designers make a mistake? Share your thoughts as comments to the blog.

Related Topics >>