Autoboxing is a term in Java which is used to refer automatic conversion of primitive type value to its wrapper class object. This automatic conversion is done internally by the Java compiler.
In the same manner, conversion of a wrapper class object to its primitive type is called unboxing in Java.
Lets understand it by a simple example.
In Java, each primitive type has its wrapper class. See the below table to understand available wrapper classes. All the wrapper classes belong to java.lang package.
# | Primitive Type | Wrapper Class |
---|---|---|
1 | byte | Byte |
2 | short | Short |
3 | char | Character |
4 | int | Integer |
5 | long | Long |
6 | float | Float |
7 | double | Double |
8 | boolean | Boolean |
The Java compiler applies autoboxing when a primitive value is:
Let's see the both scenario in the below example.
Output:
In the above example, equal() method takes two parameters one is object of Integer class and second is primitive type int. At the time of calling, we provide both the arguments as primitive int type then Java compiler internally performed autoboxing and pass first argument as an object of Integer wrapper class.
The Java compiler applies unboxing when an object of a wrapper class is:
Let's see the both scenario in the below example.
Output:
In the above example, equal() method takes two primitive type parameters. At the time of calling, we provide first argument as a wrapper class object and other one as primitive type then Java compiler internally performed unboxing and pass first argument as a primitive argument.