Sub topic 3
Autoboxing and Unboxing: What the Compiler Does for You
This chapter assumes you know Java primitive types such as int and long, basic classes and objects, == and equals, and generic collections such as List<Integer>. The goal is to make implicit primitive-to-object conversions visible so you can predict their behavior and failures.
The two conversions
A primitive is a value stored directly, such as an int containing 42. A wrapper is an object that contains a value, such as an Integer containing 42. Java provides wrapper classes because many APIs, especially generic collections, work with objects rather than primitives.
Autoboxing converts a primitive into its wrapper object. Unboxing converts a wrapper object into its primitive value.
| Java expression | Conversion |
|---|---|
| `Integer boxed = 42;` | `int` to `Integer`, called autoboxing |
| `int value = boxed;` | `Integer` to `int`, called unboxing |
| `numbers.add(7);` | `int` to `Integer` before the method call |
The compiler inserts these conversions when the surrounding context requires them.
What the compiler inserts
Consider this program:
import java.util.ArrayList;
import java.util.List;
public class BoxingBasics {
public static void main(String[] args) {
Integer boxed = 42;
int primitive = boxed;
List<Integer> numbers = new ArrayList<>();
numbers.add(7);
int first = numbers.get(0);
System.out.println(boxed + primitive + first);
}
}Conceptually, Java translates the important lines like this:
Integer boxed = Integer.valueOf(42);
int primitive = boxed.intValue();
List<Integer> numbers = new ArrayList<>();
numbers.add(Integer.valueOf(7));
int first = numbers.get(0).intValue();The source code looks as if primitives and objects are interchangeable. They are not. The compiler only adds the required method calls for you.
Autoboxing uses a factory method such as Integer.valueOf, not necessarily a new object expression. Unboxing calls a method such as intValue, longValue, or doubleValue, depending on the wrapper type.
This also explains why generic collections use wrapper types:
List<Integer> values = new ArrayList<>();
values.add(10); // boxes the int 10
int total = values.get(0); // unboxes the returned IntegerList<int> is invalid because Java generics require reference types. Integer supplies the object type that the collection needs.
Unboxing and null
Every wrapper reference can be null. A primitive cannot. If Java must unbox a null wrapper, the generated method call has no object on which to operate, so Java throws NullPointerException.
import java.util.HashMap;
import java.util.Map;
public class NullUnboxing {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 3);
Integer quantity = stock.get("pear"); // null
System.out.println(quantity); // prints null
// int unsafe = quantity; // NullPointerException
int safe = stock.getOrDefault("pear", 0);
System.out.println(safe); // prints 0
}
}The commented assignment is effectively:
int unsafe = quantity.intValue();Check for null, use a default value, or keep the result as an Integer when absence is meaningful.
Boxing in expressions
Conversions can also occur inside expressions:
Integer count = 5;
count++; // approximately: count = Integer.valueOf(count.intValue() + 1);The old Integer is unboxed, incremented as an int, and then the result is boxed again. Similar conversions occur when a wrapper participates in arithmetic with a primitive.
For predictable code, use primitives for calculations when null is not a valid state. Use wrappers at boundaries that require objects, such as generic collections or APIs where a missing value must be represented.
Exercise
What does int result = list.get(0); require when list has type List<Integer>, and what happens if the element is null?
Show answer
list.get(0) returns an Integer, so Java inserts a call to intValue() to unbox it. If the element is null, that call throws NullPointerException.