Nelz's Blog

Mah blogginess

Java 5 Auto-Unbox Is Not NULL Safe


I am kinda getting fed up with the way the language implementers of Java continually add all these conveniences, but leave them 1/2 baked.


01public class UnboxTest {
02    @Test
03    public void testUnbox() {
04        final Integer a = Integer.valueOf(10);
05        final Integer b = null;
06        unboxIt(a);
07        unboxIt(b);
08    }
09    void unboxIt(final int value) {
10        System.out.println("Value: " + value);
11    }

Guess what happens when you run this code?

A big, fat NullPointerException on line 7.

Oh yeah… Autoboxing is supposed to be soo helpful, but they can’t default a frigging null to the default value of an int. (I.e. 0)

See my previous post for similar problems in the Java 5 foreach syntax.