Auto boxing

In java every primitive type has its wrapper class. You can store the value in both forms. You can use the object of the wrapper class to hold the value or you can use the primitive type variable. To do this you have to create the object manually and the value is passed to the constructor. If you want to get the value stored in the wrapper class then you have to call the parser method to convert into primitive type.

For example

Integer in=new Integer(234);

int a=in.intValue();

But now you don’t need to bother about conversion. Compiler has the feature through which it makes the automatic conversion between primitive types and its corresponding wrapper classes. So automatically storing the primitive types value into object of corresponding wrapper class is class the auto-boxing and automatically retrieval of value into primitive type form object of corresponding wrapper class is called un-boxing. There following difference between old and new way to conversation.

With Autoboxing
Without Autoboxing
int i;
Integer j;
i = 1;
j = 2;
i = j;
j = i;
int i;
Integer j;
i = 1;
j = new Integer(2);
i = j.intValue();
j = new Integer(i);

public class AutoBoxing
    public static void main(String ar[])
        int a=100;
        Integer in=new Integer(200);
        //unboxing value 200
        int b=in;
        //autoboxing value of a
        Integer in2=new Integer(a);
        int c=in2;

No comments:

Popular Posts