95
Autoboxing and Unboxing:
The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java programmer doesn’t need to write the conversion code.
Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is required. |
Simple Example of Autoboxing in java:
Output:50 5
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. Let’s see the example of unboxing:
Output:
50
Autoboxing and Unboxing with comparison operators
Autoboxing can be performed with comparison operators. Let’s see the example of boxing with comparison operator: |
Output:50
Autoboxing and Unboxing with method overloading
In method overloading, boxing and unboxing can be performed. There are some rules for method overloading with boxing:
|
1) Example of Autoboxing where widening beats boxing
If there is possibility of widening and boxing, widening beats boxing. |
Output:int
2) Example of Autoboxing where widening beats varargs
If there is possibility of widening and varargs, widening beats var-args. |
Output:int int
3) Example of Autoboxing where boxing beats varargs
Let’s see the program where boxing beats variable argument: |
Output:Integer
Method overloading with Widening and Boxing
Widening and Boxing can’t be performed as given below: |
Output:Compile Time Error
Next TopicEnum In Java