Javatpoint Logo
Javatpoint Logo

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:

Test it Now
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:

Test it Now
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:
Test it Now
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:
  • Widening beats boxing
  • Widening beats varargs
  • Boxing beats varargs

1) Example of Autoboxing where widening beats boxing

If there is possibility of widening and boxing, widening beats boxing.
Test it Now
Output:int

2) Example of Autoboxing where widening beats varargs

If there is possibility of widening and varargs, widening beats var-args.
Test it Now
Output:int int

3) Example of Autoboxing where boxing beats varargs

Let's see the program where boxing beats variable argument:
Test it Now
Output:Integer

Method overloading with Widening and Boxing

Widening and Boxing can't be performed as given below:
Test it Now
Output:Compile Time Error
Next TopicEnum In Java




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials