JDK 1.5 provides a collection of very nice language additions and I've become an early adopter of many of them. I recently began having my doubts about auto-unboxing of reference variables though.
Consider the following class:
private T mResult;
/* do some stuff and return a result */
and then some code that uses it:
AutoUnbox<Boolean> a = new AutoUnbox<Boolean>();
if (true == a.getResult())
This looks quite harmless, doesn't it? Well you have a totally invisible
NullPointerException that is lurking in this code. If the
getResult() method returns
null, the conversion to a primitive will throw a
NullPointerException. The biggest issue with this is that it happens behind the scenes. I'm used to thinking about references that might be null when I call a method upon them. As soon as I type the dot operator, my mind thinks about the context and considers if I shouldn't perform a nullcheck first. With auto-unboxing, there is nothing that indicates that you should be careful. It could literally happen anywhere.
Imho JDK 1.5 is wrong about this and instead of throwing the NPE it should return an unintialized primitive, just as
null is the uninitialized value for a reference.
I mean, look at this code:
public class Uninit
public static void main(String args)
public void method()
false which means that there are default values defined for unitialized primitives. To me, when thinking about unboxing a
null reference to a primitive I always expected to get this 'empty' value, not a NPE.
I think I'm going to submit a bugreport to Sun about this, what do you think?