Autoboxing and Unboxing
Collections and generics can only hold objects, so Java wraps primitive values in objects such as Integer and unwraps them again, automatically, since Java 5. The conversion is invisible in the source code, which is exactly why it causes bugs: == that works for 127 but not 128, NullPointerExceptions on lines with no visible object, and loops that run several times slower. This page shows what the compiler really generates and each trap that follows from it.
Contents
Primitives, wrapper classes and why boxing exists
Java's eight primitive types (intdoubleList<T>Map<K, V>
| Primitive | Wrapper | Values cached by valueOf |
|---|---|---|
boolean | Boolean | Both (TRUEFALSE |
byte | Byte | All 256 |
short | Short | -128 to 127 |
int | Integer | -128 to 127 (upper bound configurable) |
long | Long | -128 to 127 |
char | Character | 0 to 127 |
float | Float | None |
double | Double | None |
A wrapper object costs memory: an Integerintnull
What the compiler generates
Autoboxing is a compile-time feature: the JVM knows nothing about it. To see this, the program compiles a three-line method with javac and disassembles it with javap, both run from inside Java through java.util.spi.ToolProvider
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;
// Compiles a tiny class and disassembles it with javap to show the hidden calls
public class WhatCompilerGenerates {
static final String SOURCE = """
import java.util.List;
import java.util.ArrayList;
class Boxing {
int run() {
List<Integer> list = new ArrayList<>();
list.add(42); // int -> Integer
int x = list.get(0); // Integer -> int
return x + 1;
}
}
""";
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("boxing");
Files.writeString(dir.resolve("Boxing.java"), SOURCE);
run("javac", "-d", dir.toString(), dir.resolve("Boxing.java").toString());
String code = run("javap", "-c", "-cp", dir.toString(), "Boxing");
code.lines()
.filter(l -> l.matches(".*(invoke|checkcast|iadd).*"))
.map(l -> l.replaceAll("\\s+//", " //").strip())
.forEach(System.out::println);
}
static String run(String tool, String... args) {
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
ToolProvider.findFirst(tool).orElseThrow().run(pw, pw, args);
pw.flush();
return out.toString();
}
}
Output:
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: invokespecial #9 // Method java/util/ArrayList."<init>":()V
11: invokestatic #10 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
14: invokeinterface #16, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
22: invokeinterface #22, 2 // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
27: checkcast #11 // class java/lang/Integer
30: invokevirtual #26 // Method java/lang/Integer.intValue:()I
36: iadd
becamelist.add(42) followed byInteger.valueOf(42) . Boxing always usesList.add(Object) , which is where the cache comes in.valueOf becameint x = list.get(0) , aList.get tocheckcast (because of generic type erasure), and thenInteger . ThatintValue() call is the hidden method call that throwsintValue() when the value isNullPointerException .null- The addition
is a plainx + 1 on primitives: arithmetic always happens on unboxed values.iadd
Boxing in practice, and == on wrappers
The program boxes and unboxes through a list and arithmetic, then compares Integer==
import java.util.ArrayList;
import java.util.List;
public class BoxingBasics {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(5); // autoboxing: Integer.valueOf(5)
int first = list.get(0); // unboxing: list.get(0).intValue()
System.out.println("first = " + first);
Integer boxed = 10;
int doubled = boxed * 2; // unboxed for arithmetic
System.out.println("doubled = " + doubled);
// The Integer cache: valueOf returns shared objects for -128..127
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println("127 == 127: " + (a == b));
System.out.println("128 == 128: " + (c == d));
System.out.println("128 equals 128: " + c.equals(d));
// Mixed comparison: == between Integer and int unboxes, so it compares values
int plain = 128;
System.out.println("Integer 128 == int 128: " + (c == plain));
}
}
Output:
first = 5
doubled = 20
127 == 127: true
128 == 128: false
128 equals 128: true
Integer 128 == int 128: true
- Boxing and unboxing happen without any code:
,list.add(5) andint first = list.get(0) all compile and work.boxed * 2 on two== objects compares references, not values. For 127 both variables got the same cached object fromInteger , so it printedvalueOf ; 128 is outside the cache, so two separate objects were created and it printedtrue . Code that compares IDs withfalse passes every test with small numbers and fails in production with large ones.== compares values and is correct for any number.equals unboxes theInteger == int and compares numbers, so it printedInteger . The rule: if either side oftrue is a primitive, it is a numeric comparison; if both are wrappers, it is an identity comparison.==
The caches in detail
Every wrapper's valueOfvalueOfInteger
public class CacheRanges {
public static void main(String[] args) {
// valueOf (and therefore autoboxing) reuses objects for small values
Integer a = 127;
Integer b = 127;
System.out.println("Integer 127 same object: " + (a == b));
Integer c = 128;
Integer d = 128;
System.out.println("Integer 128 same object: " + (c == d));
Integer e = -128;
Integer f = -128;
System.out.println("Integer -128 same object: " + (e == f));
Long g = 127L;
Long h = 127L;
System.out.println("Long 127 same object: " + (g == h));
System.out.println("Character 127 same object: "
+ (Character.valueOf((char) 127) == Character.valueOf((char) 127)));
System.out.println("Character 128 same object: "
+ (Character.valueOf((char) 128) == Character.valueOf((char) 128)));
System.out.println("Boolean true same object: " + (Boolean.valueOf(true) == Boolean.TRUE));
Double x = 1.0;
Double y = 1.0;
System.out.println("Double 1.0 same object: " + (x == y));
}
}
Output:
Integer 127 same object: true
Integer 128 same object: false
Integer -128 same object: true
Long 127 same object: true
Character 127 same object: true
Character 128 same object: false
Boolean true same object: true
Double 1.0 same object: false
- The Java Language Specification (section 5.1.7) requires that boxing a constant of type
,int ,short orbyte from -128 to 127 always gives the same object, and the same forlong values up to 127 and forchar andtrue ;false uses the same cache for computed values. The output matches: -128 and 127 were shared, 128 was not.valueOf andDouble have no cache, so even 1.0 gave two different objects.Float
public class CacheMax {
public static void main(String[] args) {
// Run with -XX:AutoBoxCacheMax=1000 to cache Integer values up to 1000
Integer a = 128;
Integer b = 128;
Integer c = 1000;
Integer d = 1000;
Integer e = 1001;
Integer f = 1001;
System.out.println("128 same object: " + (a == b));
System.out.println("1000 same object: " + (c == d));
System.out.println("1001 same object: " + (e == f));
}
}
Output, run with java -XX:AutoBoxCacheMax=1000 CacheMax
128 same object: true
1000 same object: true
1001 same object: false
With the option, Integer==
The constructors such as new Integer(5)synchronized
Traps: null, overloading and equals across types
Each trap in this program comes from a conversion the source code does not show. They were chosen because each one has caused real production bugs.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BoxingTraps {
static String which(long value) {
return "which(long)";
}
static String which(Integer value) {
return "which(Integer)";
}
public static void main(String[] args) {
// 1. Unboxing null throws
Map<String, Integer> stock = new HashMap<>();
try {
int apples = stock.get("apple");
System.out.println(apples);
} catch (NullPointerException e) {
System.out.println("unboxing a missing map value: NullPointerException");
}
System.out.println("safer: " + stock.getOrDefault("apple", 0));
// 2. remove(int) vs remove(Object)
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30));
nums.remove(1); // index 1
System.out.println("remove(1): " + nums);
nums.remove(Integer.valueOf(10)); // the value 10
System.out.println("remove(Integer.valueOf(10)): " + nums);
// 3. A ternary mixing int and Integer unboxes the Integer
Integer maybe = null;
boolean useDefault = false;
try {
Integer result = useDefault ? 0 : maybe;
System.out.println(result);
} catch (NullPointerException e) {
System.out.println("ternary with int and null Integer: NullPointerException");
}
// 4. equals across types is false even for the same number
Long big = 1L;
Integer small = 1;
System.out.println("Long 1 equals Integer 1: " + big.equals(small));
System.out.println("Long 1 == 1L after unboxing: " + (big == 1L));
// 5. Overload resolution prefers widening (int -> long) over boxing (int -> Integer)
System.out.println("which(5) calls " + which(5));
}
}
Output:
unboxing a missing map value: NullPointerException
safer: 0
remove(1): [10, 30]
remove(Integer.valueOf(10)): [30]
ternary with int and null Integer: NullPointerException
Long 1 equals Integer 1: false
Long 1 == 1L after unboxing: true
which(5) calls which(long)
- Unboxing null:
returnedstock.get("apple") because the key is missing, and assigning it to annull calledint onintValue() . The line contains no visible method call, which makes the stack trace confusing. Usenull , or keep the value asgetOrDefault and check forInteger .null - remove(int) or remove(Object):
has both.List<Integer> chosenums.remove(1) and removed 20, the element at index 1, not the value 1. To remove a value, pass anremove(int index) :Integer .remove(Integer.valueOf(10)) - The ternary operator:
has anuseDefault ? 0 : maybe on one side and anint on the other, so the rules make the whole expression anInteger , andint is unboxed even though the result is assigned to anmaybe . WithInteger beingmaybe , that throws. Writingnull makes both sidesInteger.valueOf(0) and avoids it.Integer - equals across types:
isLong.equals(Integer) even for the same number, becausefalse first checks the class. This bites when aequals is queried with anMap<Long, ...> key:int boxes tomap.get(5) and never matches. ComparingInteger unboxes and works.big == 1L - Overloading: given
andwhich(long) , the callwhich(Integer) chosewhich(5) . Java first looks for a method reachable by widening only, and considers boxing only if none exists. This rule, from Java 5, kept old code that relied on widening working unchanged.which(long)
The cost of boxing
Each box is an object allocation, and each unbox is a memory read through a reference. The program sums 50 million numbers with a longLongList<Integer>int[]
import java.util.List;
import java.util.stream.IntStream;
public class BoxingCost {
static long sumBoxed(int n) {
Long total = 0L; // boxed accumulator: a new Long on most additions
for (int i = 0; i < n; i++) {
total += i;
}
return total;
}
static long sumPrimitive(int n) {
long total = 0L;
for (int i = 0; i < n; i++) {
total += i;
}
return total;
}
interface Job {
long run();
}
// Best of 3 runs, so JIT compilation is not part of the measurement
static void time(String name, Job job) {
long best = Long.MAX_VALUE;
long result = 0;
for (int run = 0; run < 3; run++) {
long t = System.nanoTime();
result = job.run();
best = Math.min(best, System.nanoTime() - t);
}
System.out.printf("%-34s %,d ms (sum %d)%n", name, best / 1000000, result);
}
public static void main(String[] args) {
int n = 50000000;
time("long accumulator", () -> sumPrimitive(n));
time("Long accumulator", () -> sumBoxed(n));
List<Integer> boxedList = IntStream.range(0, 5000000).boxed().toList();
int[] primitives = IntStream.range(0, 5000000).toArray();
time("Stream<Integer> of 5M, mapToLong", () ->
boxedList.stream().mapToLong(Integer::longValue).sum());
time("IntStream over int[5M]", () -> IntStream.of(primitives).asLongStream().sum());
}
}
Output (2-CPU Linux machine, JDK 21; times will differ on yours):
long accumulator 13 ms (sum 1249999975000000)
Long accumulator 80 ms (sum 1249999975000000)
Stream<Integer> of 5M, mapToLong 10 ms (sum 12499997500000)
IntStream over int[5M] 1 ms (sum 12499997500000)
- With a
accumulator,Long means unbox, add, and box a newtotal += i , because values above 127 are not cached. Changing one letter,Long toLong , made the loop several times faster and created no garbage.long - Summing the boxed list read every
through a reference; theInteger version read contiguous memory and was much faster again. Primitive streams (int[] ,IntStream ,LongStream ) and methods such asDoubleStream exist to avoid boxing in stream pipelines.mapToInt - The JIT compiler can sometimes remove boxing through escape analysis, but it cannot be relied on, especially when boxed values are stored in collections.
Rules of thumb
| Situation | Do |
|---|---|
| Comparing two wrapper values | a.equals(b)Objects.equals(a, b)Integer.compare== |
| Reading from a map of numbers | getOrDefaultnull |
| Local variables, counters, accumulators | Primitive types |
| Large amounts of numeric data | Primitive arrays or primitive streams |
| A value that may be absent | A wrapper (can be nullOptionalInt |
Map keys of type Long | Query with long5Lint |
Removing a number from a List<Integer> | remove(Integer.valueOf(x)) |
| Creating wrappers | Autoboxing or valueOf |
Related pages: