Autoboxing in Java

Autoboxing is a new feature was added to Java 5 (or Java 1.5) which made working with primitive wrapper classes much easier for programmers. Before Java 5, if you had an Integer object for example, then to assign it to an int variable, you had to do the conversion manually,

Integer iObj = new Integer(10);
int i = iObj.intValue();

But as of Java 5, you can just write,

Integer iObj = new Integer(10);
int i = iObj;        //auto unboxing

The conversion will automatically be done for you.

The automatic conversion of primitive value to a wrapper value and vice-versa are called AutoBoxing and AutoUnboxing respectively. So the following code written for Java 1.4 and earlier,

Integer iObj = new Integer(10);
int i = iObj.intValue();

can be written as the following in Java 5 or later,

Integer iObj = 10;   //auto boxing
int i = iObj;        //auto unboxing

So who does this conversion? You guessed it right, its the compiler. When you compile your program, the compiler adds the call to intValue() for you. This way converting a primitive to a wrapper and vice-versa have become much easier. Remember that the auto boxing operation isn’t done through the new operator. So the above code will be converted to this code by the compiler

Integer iObj = Integer.valueOf(10); //conversion through valueOf
int i = iObj.intValue();

This has effect in case the value is between -128 to 127. The JVM creates a cache or pool of wrapper objects in that range to improve performance.

Rules For Autoboxing and Auto Unboxing

These automatic conversions apply to all primitive types. But there are some rules. While boxing, the primitive value must be assignable to the wrapper type. This especially kicks in for Long type. The code,

Long lObj = 10;

will fail to compile. The value 10 is an int literal, so it cannot be directly converted to type Long. So you can either use the L suffix (if the value is a literal) or you can use a type cast (generally when you are autoboxing from a variable). So the code can be compiled by any of the two changes,

Long lObj1 = 10L;
int i = 10;
Long lObj2 = (long)i;

Similar rules apply during unboxing. The following assignment will fail to compile,

Long lObj1 = 10L;
int i = lObj1;       //error

The Long type cannot be automatically unboxed to int. So what’s the solution? You can use clumsy casts like this,

Long lObj1 = 10L;
int i = (int)(long)lObj1;

But its better to do the unboxing yourself in such cases (by calling intValue on the Long object).

Leave a Comment