Autoboxing and Unboxing in Java

With Java 1.5, autoboxing and unboxing are introduced  to automatically convert the primitive type into boxed wrappers or vice versa.

Autoboxing:  It is the process of converting primitives to their corresponding object type automatically.

Unboxing: It is the process of converting object types to their corresponding primitives automatically.

Autoboxing and Unboxing


int intA = 5;
Integer integerA = intA;  // autoboxing

Integer integerB = 10;
int intB = integerB;  //unboxing

Why do we need autoboxing and unboxing?

Unfortunatelly, having primitives in Java is nothing to do with object oriented programming. The only reason comes into mind is performance, since all local primitives are allocated in jvm stack(fast) whereas all objects are preserved in heap(referenced/slow).

Primitives are generally different in size whereas since object wrappers are just references, they are equal in size.

As of Java 8 you cannot use primitives for generic types.

List<int> myList = new ArrayList<>(); //compilation error

List<Integer> myList = new ArrayList<>(); //successfully compiled

The reason is that the generic types are compiled to object which have to have same size.
For conveince Java provides us autoboxing and unboxing so that we can work with primitives and generic types with ease.

List<Integer> myList = new ArrayList<>();
int a =5;
myList.add(a); //autoboxing
int b = myList.get(0); //unboxing
System.out.println(b);  //5