Autoboxing is the automatic conversion of a primitive to its wrapper class, such as int to Integer. Unboxing is the reverse, from Integer back to int. It lets you put primitives into collections, which only hold objects.
The compiler inserts the calls for you. Boxing an int becomes Integer.valueOf(x), and unboxing becomes x.intValue().
Two traps follow from this. Unboxing a null wrapper throws a NullPointerException. Comparing two Integer objects with == compares references, and it only seems to work for small values because Integer.valueOf caches -128 to 127.
// Autoboxing
Integer num = 100; // int to Integer
List<Integer> list = new ArrayList<>();
list.add(50); // int automatically boxed to Integer
// Unboxing
Integer wrapper = 200;
int primitive = wrapper; // Integer to int
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
The diagram below the answer is the concept .
Jump to it ↓
Tailored explanation · switch back to · ·
What should the new diagram focus on?
See it - interactive diagram
Why == works for 127 but not 128
Boxed from 127Integer a = 127, b = 127;
Stack
a2
b2
Heap
1IntegerCache
low-128
high127
slot for 1272
2Integer
value127
Each boxing calls Integer.valueOf(127), which returns the same cached object. So a == b is true.
Boxed from 128Integer a = 128, b = 128;
Stack
a3
b4
Heap
1IntegerCache
low-128
high127
3Integer
value128
4Integer
value128
128 is not cached, so each valueOf call makes a new object. Both hold 128, but a == b is false.
1step
Boxed from 127: Each boxing calls Integer.valueOf(127), which returns the same cached object. So a == b is true.
1 / 2← → keys
== checks if two variables point at the same object, not if their values match. valueOf caches only -128 to 127, so a == b is true for 127 but false for 128.