Archive

Posts Tagged ‘autobox’

Autoboxing / Unboxing gotchas

August 20th, 2009 6 comments

Java introduced the concept of autoboxing and unboxing since JDK 5. It has been used quite liberally by developers ever since. But those that do not understand the difference between primitives and Wrapper types can end up misusing it. They can especially become dangerous when coupled with a framework that provides some sort of type mapping, such as entity EJBs that map Wrappers to table columns.

Let us look at some of the gotchas

Gotcha 1:

public static void main(String[] args) throws Exception
{
    Test test = new Test();
    int autobox = test.autobox();
}
private Integer autobox()
{
    return null;
}

What could possibly be the output of this program ? Well, let me not leave you guessing

Exception in thread "main" java.lang.NullPointerException
	at com.tests.Test.main(Test.java:4)

As a java programmer, when I see this exception stack trace I immediately think ‘Hmm… the test reference must have become null somehow’ without realizing that unboxing the null to a primitive failed. I could end up wasting time analyzing something that is perfectly all right, if I do not have a look at the autobox() method first.

Categories: java Tags: , , ,