Tuesday, August 7, 2007

JAVA 5.0 Autoboxing/Unboxing

What is Boxing?
Converting a primitive type to it's wrapper class is known as Boxing. For example converting from int to Integer, float to Float, double to Double etc.

What is unboxing?
The reciprocal of Boxing is called unboxing, means converting from some wrapper class to it's respective primitive type is known as unboxing. For example converting from Integer to int, Float to float, Double to double etc.

In the earlier versions from JDK 1.5 , boxing and unboxing was manual. You have to explicitly convert from one into another. But in JDK 1.5 boxing and unboxing is automatic and the compiler will do this itself on your behalf.

Example of Manual Boxing/unboxing:

int a = 2;
int b;
Integer aW = Integer(a); // This is example of boxing

b =aW.intValue(); // This is an example of unboxing.

If you want to store int values of some range say 0-100 in an ArrayList, then what you need to do ? Certainly you will make the wrapper objects of Integer class and will add them into an array list like here

ArrayList list = new ArrayList();
for(int i = 0; i <100;i++)
list.add(
new Integer(i));// You can pass only Objects into add method // not primitives
}

This is basically boxing. Similarly if you want to add the elements of the ArrayList into some int variable then you need to do the unboxing like shown here:

sum += ((Integer)list.get(i)).intValue();

But if you are using JAVA 5.0, all of these will be done automatically by the compiler on your behalf like shown here:

ArrayList list = new ArrayList();
for(int i = 0; i <100;i++)
{
list.add(i); // AutoBoxing is done here
}

int sum = 0;
for
( Integer j : list)
{
sum += j; // Auto-unboxing is done here..
}

For further reference Read the SUN DOCUMENTATION from the following link:

http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html



No comments: