Google+

250. Boxing and UnBoxing








Pre-requisites -


Boxing is the process of wrapping the primitive data type value into Wrapper Class object using any Wrapper Class.

Example -

Integer obj = new Integer(100);  //Wrapping primitive data type value 100 using Integer Wrapper Class into object obj

UnBoxing is the process of unwrapping the wrapped Wrapper Class object back to the primitive data type value.

Example -

int var = obj.intValue( ); //Unwrapping Integer Wrapper Class object obj back to primitive data type value 100

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Class 'BoxingUnBoxingDemo.java' in the existing Java Project 'Wrapper Class' as shown below -


2. Implement Boxing by Wrapping an int primitive data type value '100' into an object using Integer Wrapper Class as shown below -


3. Print the integer value 100 using wrapped object obj as shown below -


4. Save & Run the Java Class 'BoxingUnBoxingDemo.java' and observe that the integer value 100 is printed using the obj object as shown below -


Now lets implement the process of UnBoxing using the below steps.

5. Implement UnBoxing using the intValue( ) method which unwraps the object obj back to the integer data type as shown below -


6. Print the integer value 100 using unwrapped int primitive data type var as shown below -


7. 
Save & Run the Java Class 'BoxingUnBoxingDemo.java' and observe that the integer value 100 is printed using the integer primitive data type variable var as shown below -


Hence Boxing is the process of wrapping the primitive data type into objects using Wrapper Classes and Unboxing is the process of unwrapping the objects of Wrapper Classes back to primitive data type.







Please comment below to feedback or ask questions.

AutoBoxing will be explained in the next post.







No comments:

Followers :)

Blog Index