Ben Galbraith’s Blog

Autoboxing Makes Null Fun!

with 2 comments

Among the wonderful changes in Java 5 that make code easier to read and maintain (cough) is autoboxing. Consider the following line of code:

return handleIncorrectType(message, modelColumn, o, keyboard);

It was throwing a NullPointerException (not passing one from the underlying method invocation). I had to scratch my head for quite a few minutes to see how it would, as there was no invocation on the parameters that could cause it.

The answer was that one of the parameters was a primitive wrapper type (Boolean) set to a null value, and the autoboxing mechanism punts when coalescing wrapper nulls to primitive types. Fun!

Written by Ben Galbraith

March 17, 2007 at 12:07 pm

Posted in Technology

2 Responses

Subscribe to comments with RSS.

  1. What would you rather it did?

    Ricky Clarkson

    March 17, 2007 at 9:43 pm

  2. Perhaps throw something like a WrapperNullException with a message like “A primitive wrapper type contained a null value and could not be coerced to a primitive.”

    Nah, that would be too clear. Better to throw an NPE with no specific explanation.

    Ben Galbraith

    March 17, 2007 at 10:06 pm


Leave a Reply