What exactly are autoboxing and unboxing in Java, and where does the compiler insert them for you?
Autoboxing is the compiler turning a primitive value into its wrapper object. Unboxing is the compiler doing the opposite. Neither of them exists in the bytecode as an operator. The compiler rewrites them into an ordinary static factory call and an ordinary instance method call. So the line Integer x = 5; really becomes the line Integer x = Integer.valueOf(5);, and the line int y = x; really becomes the line int y = x.intValue();.
The compiler puts these conversions in three places.
- In assignments and in initialisations. That is the example above. An
intthat is given to anIntegervariable is boxed, and anIntegerthat is given to anintvariable is unboxed. - In method calls. This happens when the type of the argument and the type of the parameter differ only by boxing. Giving an
intto a method that wants anIntegerboxes it, and giving anIntegerto a method that wants anintunboxes it. - In the compound assignment operators. The line
x += 1on a wrapper is compiled as the linex = x + 1, so it unboxes the wrapper, does the addition, and then boxes the answer again.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int raw = 7;
List<Integer> counts = new ArrayList<>();
counts.add(raw); // autoboxing: int becomes Integer
int back = counts.get(0); // unboxing: Integer becomes int
System.out.println("round trip : " + back);
Integer boxed = 42; // autoboxing on an assignment
int unboxed = boxed; // unboxing on an assignment
System.out.println("assignment : " + unboxed);
// A compound assignment unboxes, adds, and then boxes again.
Integer counter = Integer.valueOf(0);
counter += 5;
System.out.println("counter += 5 : " + counter);
// Which overload is chosen also depends on the boxing.
System.out.println("overload : " + describe(7));
System.out.println("overload : " + describe(Integer.valueOf(7)));
}
static String describe(int value) { return "int overload"; }
static String describe(Integer v) { return "Integer overload"; }
}
The overload case is the sneaky one. Because both an int version and an Integer version of the method exist, the compiler picks the primitive version for an int argument and the wrapper version for an Integer argument, and it does not report any ambiguity at all. That is why an API that offers both overloads behaves differently depending on whether the caller boxed the value first.
The next question in this topic looks at whether writing the conversion out by hand is ever better.