Autoboxing & Unboxing
TL;DR
- Autoboxing: The automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes (e.g.,
int->Integer). - Unboxing: The reverse process. Automatically converting an object of a wrapper class to its corresponding primitive type (e.g.,
Integer->int).
Concept
Introduced in Java 5, autoboxing and unboxing let developers write cleaner code. Without them, you would have to manually instantiate wrapper classes every time you wanted to put a primitive into a Collection.
Under the hood, the compiler inserts Integer.valueOf() for boxing, and .intValue() for unboxing.
Examples
import java.util.ArrayList;
import java.util.List;
public class AutoboxingExample {
public static void main(String[] args) {
// --- Autoboxing ---
Integer wrapperInt = 10;
// Behind the scenes: Integer wrapperInt = Integer.valueOf(10);
List<Integer> list = new ArrayList<>();
list.add(5); // Autoboxing: 5 is converted to Integer(5)
// --- Unboxing ---
int primitiveInt = wrapperInt;
// Behind the scenes: int primitiveInt = wrapperInt.intValue();
// Math operations automatically unbox
Integer a = 10;
Integer b = 20;
int sum = a + b; // Both 'a' and 'b' are unboxed to int before addition
}
}
Interview Questions
Q: What happens if you try to unbox a null wrapper object?
A: It throws a NullPointerException. This is a common pitfall. If you have an Integer that is null, and you attempt to assign it to an int primitive, the compiler attempts to call .intValue() on the null object, causing a crash.
Q: How does Autoboxing impact performance?
A: While autoboxing makes code cleaner, it can be detrimental to performance inside a heavy loop. Autoboxing creates a brand new Object on the heap. Doing this millions of times in a loop will cause unnecessary memory allocation and trigger Garbage Collection frequently. It is better to use primitives for heavy math and logic.