Topic 31 of 78
Autoboxing & Unboxing
Overview
Because Wrapper classes and primitives are constantly interacting, manually wrapping and unwrapping them requires a lot of repetitive code (e.g., `Integer.valueOf(5)`). Introduced in Java 5, Autoboxing is the automatic conversion the Java compiler makes between the primitive types and their corresponding object wrapper classes. Unboxing is the reverse. It makes code immensely cleaner to read and write.
Syntax
Autoboxing allows you to seamlessly mix primitives and objects in math equations and Collections. The compiler does the heavy lifting for you.
Autoboxing and Unboxing in Action
java
List<Integer> list = new ArrayList<>();
// 1. AUTOBOXING (Primitive -> Object)
// Under the hood, Java transforms this to: list.add(Integer.valueOf(10));
list.add(10);
// 2. UNBOXING (Object -> Primitive)
// Java transforms this to: int myNum = list.get(0).intValue();
int myNum = list.get(0);
// 3. Math with Objects
Integer a = 5; // Autoboxed
Integer b = 10; // Autoboxed
// Both are unboxed to primitives, added, and the result is autoboxed back!
Integer sum = a + b;Common Pitfalls
- NullPointerExceptions during Unboxing. If an `Integer` object is `null`, and Java attempts to automatically unbox it into an `int`, the program will crash instantly because a primitive cannot hold null.
- Massive memory/performance leaks. Autoboxing inside a loop of 1,000,000 iterations creates 1,000,000 unnecessary objects in memory.
Interview Tips
- Autoboxing drastically cleans up code, but mention the hidden performance cost of creating thousands of wrapper objects in a loop.
Real-World Example
It simplifies entity mapping in ORMs like Hibernate, where database columns can be null (requiring Wrapper Objects) but business logic uses primitive math.
example
java
public class Product {
// Integer because Price in DB might be NULL
private Integer priceInCents;
public double getPriceInDollars() {
if (priceInCents == null) return 0.0;
// Unboxing happens automatically here!
// priceInCents is converted to an 'int' to do the math.
return priceInCents / 100.0;
}
}