Friday, March 24, 2006

Java Tip #9 - unboxing and the elusive npe

Be aware that unboxing can cause a NullPointerException.
Suppose I have this function.

public void test(int a) {
...
}

and I declare this variable
  Integer x = null;
then when I make this call
  test(x)
I get a NullPointerException as x is "unboxed" to an int. A more specific exception such as "NullPointerExceptionDueToUnboxingYouMoron" would have helped.

Enjoy.

2 Comments:

Blogger Avah said...

Because "unboxing" is just a call to Integer.intValue(), it just behaves the same as the method would. Boxing and unboxing don't really reflect in the resulting code, and thus boxing-specific exceptions can't be thrown by the framework..

11:54 AM  
Blogger Billy Bob Bain said...

Thanks for the comment. You are correct of course. I don't think you can tell from the classfile that there was an unboxing conversion.

JLS 5.1.8 says:
Unboxing conversion converts values of reference type to corresponding values of primitive type. The precise rules are as follows:

If r is a reference of type Boolean, then unboxing conversion converts r into r.booleanValue().
If r is a reference of type Byte, then unboxing conversion converts r into r.byteValue().
If r is a reference of type Character, then unboxing conversion converts r into r.charValue().
If r is a reference of type Short, then unboxing conversion converts r into r.shortValue().
If r is a reference of type Integer, then unboxing conversion converts r into r.intValue().
If r is a reference of type Long, then unboxing conversion converts r into r.longValue().
If r is a reference of type Float, unboxing conversion converts r into r.floatValue().
If r is a reference of type Double, then unboxing conversion converts r into r.doubleValue().
If r is null, unboxing conversion throws a NullPointerException.

8:34 AM  

Post a Comment

<< Home