Autoboxing Pitfall: Null References

This is a nifty little pitfall I discovered the other day while looking at some code.  Here's a simplified version of what I saw:

1:public class Main {
2: public static void main(String[] args) {
3: Model model = new Model();
4: int value = model.calc();
5: }
6:}

The above code throws a NullPointerException on line 4, which is where model.calc() is called.  I was a bit stumped at first.  How could an NPE get thrown when I could verify that model wasn't null?  If calc() were generating an NPE, the currently unhelpful exception text would point to a line within the calc() method instead of line 4. Out of curiosity, I jumped over to the Model class to see what calc() was doing:

public Integer calc() {
// Uninteresting code
}


Actually seeing the method declaration set off bells in my head.  What would happen if calc() returned null? Somewhere code exists that is calling something similar to Integer.intValue().  If Integer were null there's not much to be done except to throw an NPE.  In the end, simply adjusting calc() so that it never returned null was enough.

From now on, I'll be on the lookout for situations such as this.