Google+

252. Auto-Unboxing







Auto-UnBoxing is the process by which the value of the boxed object is automatically unboxed to primitive data type value. There is no need to call methods such as intValue( ), charValue( ) etc to unbox objects back to the primitive data types. Java will automatic convert the values without taking help of the above said methods. In order to understand the Auto-UnBoxing clearly, we have to first understand the manual unboxing process -

Example for Manual UnBoxing -

int var = obj.intValue( );  //UnBoxed the obj to int primitive type value using intValue( ) method

Example for Auto-UnBoxing -

int var = obj;  //Auto-UnBoxed the obj to int primitive type value without using intValue( ) method

Examples for Auto-UnBoxing objects of all Wrapper Classes back to primitive data type values -

Auto-UnBoxing different Wrapper Class objects to primitive data type values without calling methods like intValue( ), charValue( ) etc.

int var1 = obj1;
byte var2 = obj2;
short var3 = obj3;
long var4 = obj4;
float var5 = obj5;
double var6 = obj6;
char var7 = obj7;
boolean var8 = obj8;

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, open the existing Java Class 'AutoBoxing.java' in Java Project 'Wrapper Classes' as shown below -



2. Implement Auto-UnBoxing, without calling methods like intValue( ), charValue( ) etc as shown below -


3. Print all the Auto-UnBoxed primitive data types as shown below -


4. Save & Run the Java Class 'AutoBoxing.java' and observe that the primitive data type values got printed using the Auto-UnBoxed primitive data type variables as shown below -


In order to unwrap the objects into primitive data types values, we can use Auto-UnBoxing instead of manual UnBoxing. In Auto-UnBoxing, methods for unwrapping the objects to primitive data types variables like intValue( ), charValue( ) etc are not required. Instead we can directly assign Wrapper Classes defined objects to primitive data type variables. Java will automatically UnBox the Wrapper Class objects to primitive data type variable. 







Please comment below to feedback or ask questions.

Implementing AutoBoxing in methods will be explained in the next post.





No comments: