Tuesday, September 11, 2007

NPE due to autoboxing

One of the nice features of Java 5 is autoboxing. I guess everyone remembers the hassle of calling Integer.intValue() to convert from Integer to int.

Now can you guess what the following code does when you call FB.foo()?

public class FB
{
public void foo()
{
int x;
x = bar();
System.out.println("X is " + x);
}

public Integer bar()
{
return null;
}
}


Yeah, it is throwing a NullPointerException in the assignment x = bar() because bar() is returning null and the implicit bar().intValue() is thus throwing the NPE. Without autoboxing, this is much more evident.

Unfortunately it seems like FindBugs and other tools are not (yet) able to detect this (actually in my test code, FindBugs was not even able to detect the NPE in teh explicit call).

No comments:

Post a Comment