What is autoboxing and unboxing in java 5?

Before J2Se 5.0 all the primitive values like int, long , double etc are needed to convert them into the objects using wrapper classes. Suppose we want to use object or we want to put primitive values into the collection it was hard as we needed to convert primitive values into objects and then put it inside the collection, similarly when we need to use this primitive value we again need to convert it beck to the primitive value from object.

int test = 0 ;

Vector testVec = new Vector();

testVec.add( new Integer( test )); // Converted primitive value to object.
int testInt = ((Integer)testVec.elementAt(0)).intValue(); // Again converted to primitive value from objects.

From J2SE 5.0 , life is somehow easy as in J2SE 5.0 it automatically converts primitive value to object and an object to again primitive value.

AutoBoxing :

Converting primitive values like int, double, long etc to objects like Integer, Double and Long automatically called as autoboxing

Integer intObj = 7 // Auto boxing

Unboxing :

Automatically converting wrapper types into their primitive equivalents is called as Auto Unboxing

int intvalue = New Integer( 7 );

These two are very helpful in assignments , doing constructor invocations or passing argument to a method.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment