AutoBoxing and Auto-UnBoxing occurs in expressions. Lets understand it in the below example -
Example -
Integer obj1=100, obj2 = 50, obj3;
obj3 = obj1 + obj2; //Here obj1 and obj2 are auto-unboxed first, added and then autoboxed to obj3
Lets implement this on Eclipse IDE -
1. Launch Eclipse IDE, create a new Java Class 'AutoBoxedUnBoxedInExpressions.java' with main( ) method in the existing Java Project 'Wrapper Classes' as shown below -
2. Define three Integer Wrapper Class type objects and assign int primitive data type values to the two objects as shown below -
3. Add two object obj1 & obj2 and assign the result to the object obj3 as shown below -
In this step, obj1 and obj2 objects are auto-unboxed to integer data type values to get added and after adding the resultant integer data type value is autoboxed to obj3 object.
4. Print the obj3 object using the print statement as shown below -
5. Save & Run the Java Class 'AutoBoxedUnBoxedExpressions.java' and observe the value inside the object obj3 is printed as shown below -
Hence AutoBoxing and Auto-UnBoxing occurs in expressions. But, in the above example, instead of any purpose we have used Integers Wrapper Class objects for performing operations. Although the above code is technically correct, but if we have used int primitive type variables instead of objects, we would have increased the program's performance as the objects adds additional overhead to the program. So use objects instead of primitive data types, when you really need to use object in the program. Unnecessary use of objects instead of primitive data types adds additional overhead to the program and gives performance issues.
Please comment below to feedback or ask questions.
No comments:
Post a Comment