Java autoboxing and unboxing

Java Autoboxing - Primitive Type to Wrapper Object

In autoboxing, the Java compiler automatically converts primitive types into their corresponding wrapper class objects. For example,

int a = 56;

// autoboxing
Integer aObj = a;

Autoboxing has a great advantage while working with Java collections.


Example 1: Java Autoboxing

Output

ArrayList: [5, 6]

In the above example, we have created an array list of Integer type. Hence the array list can only hold objects of Integer type.

Notice the line,

list.add(5);

Here, we are passing primitive type value. However, due to autoboxing, the primitive value is automatically converted into an Integer object and stored in the array list.


Java Unboxing - Wrapper Objects to Primitive Types

In unboxing, the Java compiler automatically converts wrapper class objects into their corresponding primitive types. For example,

// autoboxing
Integer aObj = 56;

// unboxing
int a = aObj;

Like autoboxing, unboxing can also be used with Java collections.


Example 2: Java Unboxing

Output

ArrayList: [5, 6]
Value at index 0: 5

In the above example, notice the line,

int a = list.get(0);

Here, the get() method returns the object at index 0. However, due to unboxing, the object is automatically converted into the primitive type int and assigned to the variable a.