Autoboxing
J2se5 added the new feature called Autoboxing / auto-unboxing.Auto boxing is nothing but converting a primitive type automatically to its corresponding type wrapper whenever its required the type as wrapper. Hence we don’t have to create a wrapper object explicitly.The same way auto-unboxing is creating the primitive type from the wrapper when it is required; and we don’t have to call intVal() or floatValue() methods.
Lets see this with an example :
1 2 3 4 5 6 7 8 |
class AutoBoxingDemo { public static void main(String args[]) { Integer iObj=25; //Auto boxing System.out.println(iObj); } } |
Output :
25
Here in the above example while we are assigning 25 – primitive type value to the wrapper object iObj ; java convert this primitive to wrapper object automatically.
unboxing
Let’s see another example for for auto-unboxing
1 2 3 4 5 6 7 8 9 |
class AutoBoxingDemo { public static void main(String args[]) { Integer iObj=25; int i=iObj; // Auto unboxing System.out.println(i); } } |
Output :
25
Here in the above example while we are assigning a wrapper object iObj to primitive type variable; Java convert the wrapper object iObj to its corresponding primitive value.
Now we have auto boxing and auto-unboxing in from j2se5 onwards. This will lead a performance issue if we are not using it properly. Let’s see one example of bad usage of boxing and unboxing.
1 2 3 4 5 6 7 8 9 10 11 |
class Demo { public static void main(String args[]) { Integer a,b,c; a=25; b=50; c=(a+b)*2; System.out.println(“Result is ”+c); } } |
The above code is correct and it will run successfully. But this has a performance issue. The reason is that each autobox and unbox adds overhead; which is not there if we use primitive type.
Leave a Reply