Autoboxing and Unboxing in Java


Autoboxing is an automatic conversion of primitive type into its corresponding wrapper class object by the java compiler. For an example converting an int to an Integer.

Consider the following example: 

   int i = 10;
   Integer j = i;

Here, Integer j expects wrapper class of Integer object, but even though if we assign int value rather than Integer object the code compiles successfully without any errors. This is because of compiler itself creates an Integer object from i at runtime as shown below: 

   Integer i = Integer.valueOf(i);   // autoboxing


Unboxing is an automatic conversion of wrapper class object into its corresponding primitive type by the java compiler. For an example converting an Integer to an int.

Consider the following example: 

   Integer i = new Integer(10);
   int j = i; 

Here, int j expects primitive type of int value, but even though if we assign Integer object rather than int value the code compiles successfully without any errors. This is because of compiler itself creates a primitive int value from i at runtime as shown below: 

   int j = i.intValue();   // unboxing

Thus java compiler performs Autoboxing and Unboxing at runtime.

Here's the list of Primitive types with their corresponding Wrapper classes.

Primitive type Wrapper class
byte Byte
boolean Boolean
char Character
int Integer
float Float
short Short
long Long
double Double

Related Articles

post a comment