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,
But as of Java 5, you can just write,
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,
can be written as the following in Java 5 or later,
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
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,
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,
Similar rules apply during unboxing. The following assignment will fail to compile,
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,
int i = (int)(long)lObj1;
But its better to do the unboxing yourself in such cases (by calling intValue on the Long object).