Autoboxing:
The way I comprehended!
Hi rajakanak,
Simply understand that wrapper classes incapsulate the corresponding primitive data types.
You can think about a wrapper class like this:
final class Integer extends Object implements Comparable {
int a;
}
Class Integer has encapsulated the primitive type a for example, you can think so;
Using prior
Java 5.0 version we are not able to do like
Integer i1 = 5;//error, prior to Java 5.0
Primitive can�t be assigned to object reference variable;
Whereas the correct approach is
Integer i1 = Integer.valueOf(5);//takes int and returns wrapped Integer object
Or
Integer i2 = Integer.valueOf(�5�);//takes
String and returns wrapped Integer object
The valueof() is the static method of the Wrapper classes. That take corresponding primitive or String and returns the boxed object(encapsulating primitive) that we assigned to wrapper reference variable i1.
You can feel the trouble of converting a primitive to corresponding wrapper class object. But with Java 5; this happens automatically.
The primitive is automatically boxed to corresponding wrapper class object and assigned to the reference variable in our case to i2; See this:
Interger i2 = 12;//NO problem, autoboxing is done automatically
This is equivalent to
Integer i2= Integer.valueOf(12);
Finally what Boxing means: To box a primitive to the corresponding Wrapper class object. Unboxing means converting the boxed primitive object to the corresponding primitive type. And autoboxing refers to both the activity that is happening automatically without any explicit effort by the programmer. Now see these couple lines of code:
int a = new Integer(12);//unboxing takes place
This is equivalent to
int a = new Integer(12).intValue();
float b = new Float(12.33d);// unboixng takes place,
this is equivalent to
flaot b = new Float(12.33d).intValue();
I hope this helps you well.
With regards,
cmbhatt