Sub topic 3
Autoboxing and unboxing: what the compiler does for you
Prerequisites
This chapter assumes you know Java's primitive types (int, long, double, boolean, char), basic class and object syntax, how == and equals differ on objects, and how to use List and Map with generics. You should also know that each primitive has a wrapper class such as Integer or Double.
What the conversions are
Boxing wraps a primitive value in an object of its wrapper class. Unboxing extracts the primitive value from a wrapper object. Since Java 5, the compiler inserts both conversions for you when the types on either side of an assignment, a call, or an operator do not match. This feature is called autoboxing.
Autoboxing is a compile-time rewrite. The JVM never sees an implicit conversion. By the time the class file exists, every conversion is an ordinary method call.
| Primitive | Wrapper | Boxing call | Unboxing call |
|---|---|---|---|
| `boolean` | `Boolean` | `Boolean.valueOf(boolean)` | `booleanValue()` |
| `byte` | `Byte` | `Byte.valueOf(byte)` | `byteValue()` |
| `short` | `Short` | `Short.valueOf(short)` | `shortValue()` |
| `char` | `Character` | `Character.valueOf(char)` | `charValue()` |
| `int` | `Integer` | `Integer.valueOf(int)` | `intValue()` |
| `long` | `Long` | `Long.valueOf(long)` | `longValue()` |
| `float` | `Float` | `Float.valueOf(float)` | `floatValue()` |
| `double` | `Double` | `Double.valueOf(double)` | `doubleValue()` |
What the compiler emits
Take this short program.
import java.util.ArrayList;
import java.util.List;
public class BoxingBasics {
public static void main(String[] args) {
Integer boxed = 42; // autoboxing: compiled as Integer.valueOf(42)
int primitive = boxed; // unboxing: compiled as boxed.intValue()
List<Integer> numbers = new ArrayList<>();
numbers.add(7); // int boxed to Integer
int first = numbers.get(0); // Integer unboxed to int
System.out.println(boxed + primitive + first);
}
}It prints 91. You can check the rewrite yourself by compiling the class and running javap -c BoxingBasics. The first lines of main look like this:
0: bipush 42
2: invokestatic #7 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1
6: aload_1
7: invokevirtual #13 // Method java/lang/Integer.intValue:()I
10: istore_2The source shows no method calls, yet the bytecode has invokestatic Integer.valueOf and invokevirtual Integer.intValue. Every place where you see a conversion in source is a real method call, and the boxing call may allocate an object.
Where conversions happen
Conversions happen in every context where Java checks types, not only in plain assignments.
- Assignment:
Integer a = 10;boxes, andint b = a;unboxes. - Method arguments and return values: passing an
intto anIntegerparameter boxes it. Returning anIntegerfrom a method declaredintunboxes it. - Arithmetic: operators such as
+,*,<, and unary-work on primitives, so wrapper operands are unboxed first. - Conditions:
if (flag)andwhile (flag)unbox aBoolean. - Collections:
add,put,get, and the enhancedforloop cross the boundary because generic type arguments must be reference types. switch: a wrapper selector such asIntegerorCharacteris unboxed.
This program uses several of those contexts.
import java.util.ArrayList;
import java.util.List;
public class WhereBoxingHappens {
static int twice(int n) { return n * 2; }
static Integer boxedTwice(Integer n) { return n * 2; }
public static void main(String[] args) {
Integer a = 10; // boxing
int b = a + 5; // unbox a, add as ints
Integer c = a * b; // unbox both, multiply, box the result
System.out.println(twice(a)); // unbox for the int parameter
System.out.println(boxedTwice(7)); // box the argument, unbox inside, box the result
Boolean ready = true;
if (ready) { // unbox for the condition
System.out.println("ready");
}
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add(i * i); // box each int
}
int total = 0;
for (int v : list) { // unbox each element
total += v;
}
System.out.println(c + " " + total);
}
}The output is 20, 14, ready, and 150 5.
Which conversions are allowed
Boxing is stricter than primitive widening. A boxing conversion turns an int into exactly an Integer, and it never turns an int into a Long or a Double. After boxing, the compiler may still widen the reference, so an int can become an Object or a Number. In the other direction, unboxing may be followed by primitive widening, so an Integer can become a long.
public class ConversionRules {
public static void main(String[] args) {
long widened = Integer.valueOf(5); // unbox to int, then widen to long
Object o = 5; // box to Integer, then widen to Object
Number n = 3.5; // box to Double, then widen to Number
Byte small = 10; // constant fits in a byte, then boxed
Character letter = 65; // constant fits in a char: 'A'
// Long wrong = 5; // compile error: int cannot become Long
// Double alsoWrong = 1; // compile error: int cannot become Double
Long big = 5L;
Double d = 1.0;
System.out.println(widened + " " + o + " " + n + " " + small
+ " " + letter + " " + big + " " + d);
}
}It prints 5 5 3.5 10 A 5 1.0. The two commented-out lines are the errors that surprise people most. The literal 5 is an int, and int can only be boxed to Integer. Write 5L or 1.0 so the literal already has the right type.
Increments and compound assignment
Wrapper objects are immutable, so an operator can never change the object a variable refers to. When you write count++ on an Integer, the compiler unboxes the value, adds one, boxes the result, and stores the new reference in the variable.
public class ImmutableIncrement {
public static void main(String[] args) {
Integer a = 1000;
Integer b = a; // b and a refer to the same object
a++; // roughly: a = Integer.valueOf(a.intValue() + 1)
System.out.println(a + " " + b); // 1001 1000
Integer count = 0;
for (int i = 0; i < 5; i++) {
count += 2; // unbox, add, box, reassign
}
System.out.println(count); // 10
}
}The first line prints 1001 1000. The variable b still refers to the old object, which proves that a++ created a new Integer and did not modify the old one.
Mixed operands and the ternary operator
The conditional operator ? : is where silent unboxing causes the most trouble. Its result type follows numeric promotion rules, and those rules can unbox an operand you intended to keep as an object.
public class TernaryTraps {
public static void main(String[] args) {
boolean flag = true;
// Integer and Double operands are unboxed and promoted to double.
Object mixed = flag ? Integer.valueOf(1) : Double.valueOf(2.0);
System.out.println(mixed); // 1.0, not 1
// int and Integer operands give an int result, so the Integer is unboxed.
Integer missing = null;
boolean useDefault = false;
try {
int result = useDefault ? 1 : missing;
System.out.println(result);
} catch (NullPointerException e) {
System.out.println("NullPointerException from unboxing");
}
}
}The first case prints 1.0, because both branches are promoted to double even though the left branch was chosen. The second case throws, because one operand is a primitive int and the other is an Integer, so the result type is int and missing is unboxed. The same code with null as the second operand, useDefault ? 1 : null, has type Integer and does not throw.
Comparison operators mix both worlds
The relational operators <, >, <=, and >= always unbox their operands. The operators == and != behave differently depending on the operand types:
- If one operand is a primitive and the other is a wrapper, the wrapper is unboxed and the values are compared numerically.
- If both operands are wrappers, the two references are compared, and nothing is unboxed.
public class MixedComparison {
public static void main(String[] args) {
Integer boxed = 1000;
int primitive = 1000;
System.out.println(boxed == primitive); // true: boxed is unboxed first
System.out.println(boxed >= primitive); // true: relational operators unbox
}
}Comparing two wrapper references with == is a separate topic. A later chapter covers the value cache and the correct ways to compare wrappers.
What boxing does not cover
Autoboxing works on single values. It does not convert arrays, and it does not let you use primitives as type arguments.
List<int>is a compile error. UseList<Integer>.Integer[] boxes = new int[3];is a compile error, becauseint[]andInteger[]are unrelated types.Arrays.asList(new int[] {1, 2, 3})returns aList<int[]>with one element. It does not return a list of three integers. Passing separate values, as inArrays.asList(1, 2, 3), boxes each one.- Generic functional types such as
Function<Integer, Integer>box at their edges. A lambda likex -> x * 2unboxesx, multiplies, and boxes the result.
Reading boxing in your own code
When you review code, scan for the places where one side is a wrapper and the other is a primitive. Three questions find most problems:
- Could this wrapper be
nullat this point? If so, unboxing will throw. - Is this inside a loop? Each boxing call there may allocate an object.
- Does the expression mix a wrapper, a primitive, and
? :? If so, check the result type by hand.
The compiler will not warn you about any of these by default. Some IDEs and static analysis tools can flag them, and javap -c shows exactly what was generated.
Exercise
Which of these lines fail to compile? Explain each one. (1) Long a = 10; (2) long b = Integer.valueOf(10); (3) Object c = 10; (4) Double d = 10; (5) Short e = 10;
Show answer
Lines (1) and (4) fail. The literal 10 is an int, and boxing turns an int into exactly an Integer, never a Long or a Double. Line (2) compiles because the Integer is unboxed to int and then widened to long. Line (3) compiles because 10 is boxed to Integer and then widened to Object. Line (5) compiles because 10 is a constant that fits in a short, and the target is Short.
Exercise
Given Integer x = 500; Integer y = x; x += 1;, what are the values of x and y afterwards, and how many Integer objects were created for the increment?
Show answer
x is 501 and y is 500. The compound assignment unboxes x, adds 1, and boxes the result with Integer.valueOf into a new Integer object, which is then stored in x. One new Integer object is created. The object that y refers to is unchanged because wrappers are immutable.
Exercise
Why does int r = useDefault ? 1 : missing; throw when missing is a null Integer and useDefault is false, while Integer r = useDefault ? 1 : null; does not?
Show answer
In the first line, one operand is an int and the other is an Integer, so the conditional expression has type int and the null Integer is unboxed with intValue(), which throws NullPointerException. In the second line, the operands are int and the null literal, so the expression has type Integer and no unboxing takes place.