AUTOBOXING AND UNBOXING IN JAVA

When Java automatically converts a primitive type like int into corresponding wrapper class object e.g. Integer than its called autoboxing  because primitive is boxed into wrapper class while in opposite case is called unboxing, where an Integer object is converted into primitive int. All primitive types e.g. byte, short, char, int, long, float, double and boolean has corresponding wrapper class e.g. Byte, Short, Integer, Character etc and participate in autoboxing and unboxing. Since whole process happens automatically without writing any code for conversion its called autoboxing and auto unboxing.

IMPORTANT POINT ABOUT AUTOBOXING AND UNBOXING IN JAVA

1) Compiler uses valueOf() method to convert primitive to Object and uses intValue(), doubleValue() etc to get primitive value from Object.

2)  During autoboxing boolean is converted to Boolean, byte to Byte, char converted to Character, float changes to Float, int goes to Integer, long goes to Long and short converts to Short, while in unboxing opposite happens like Float to float.

 

When does autoboxing and unboxing occurs in Java

Autoboxing and unboxing can happen anywhere where an object is expected and primitive type is available for example In method invocation where an object argument is expected,  if you pass primitive, Java automatically converts primitive into equal value Object. Classic use of autoboxing is adding primitive types into Collection like ArrayList in Java or creating instance of parameterized classes e.g. ThreadLocal which expect Type. here is some code example of auto boxing and unboxing in Java:

 

Autoboxing and Unboxing Example in Java

In last section we discussed What is autoboxing and unboxing in Java and when does they occur. In short Autoboxing mainly occur in two places one is during assignment and other is during method invocation, let’s see couple of example of autoboxing and unboxing in Java to understand it better :

boxing

Autoboxing and unboxing in assignment:

This is the most common example of autoboxing in Java, earlier the code was bloated with explicit conversion which is now taken care by compiler.

Autoboxing and unboxing in method invocation:

This is another place where autoboxing makes your life easy, it allow you to pass Object or primitive interchangeably in a method without explicit conversion: