Categories
Software

Autoboxing and Unboxing in Java

In java, we often need to convert primitive types to their object(boxed wrappers) counterparts or vice versa. Unfortunately, doing these conversions all the time is tedious and make code verbose. For this reason, Java 1.5 introduced two concepts, autoboxing and unboxing, that automate these conversions.

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

examples:


int intA = 5;
Integer integerA = intA; // autoboxing
Integer integerB = 10;
int intB = integerB; //unboxing

Why do we need autoboxing and unboxing?

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

Primitives are generally different in size. On the other hand,object wrappers are just references and are equal in size.

As of Java 8 you can not use primitives for generic types. Because the generic types are compiled to object which have to have same size. However, primitive types vary in size.


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

Since autoboxing and unboxing gives us automatic conversions, we can easily work with primitive types on generic types.


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

As a result, these conversions have to be done until java allows us to use primitive types as object types.