Autoboxing
Autoboxing is Java's automatic conversion between primitive types (int, double, boolean) and their wrapper classes (Integer, Double, Boolean). Added in Java 5 to make generics and collections usable with primitive values.
Autoboxing
Integer boxed = 42; // autobox: int β Integer
List<Integer> list = new ArrayList<>();
list.add(10); // autobox: int β Integer
list.add(20);
Unboxing
int n = boxed; // unbox: Integer β int
int first = list.get(0); // unbox: Integer β int
The null trap
Integer maybe = null;
int n = maybe; // NullPointerException!
Unboxing a null wrapper throws NPE. This trips up many developers β use Optional or null checks when a wrapper might be null.
Integer cache gotcha
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true β cached!
Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false β new object each time
Java caches boxed Integers in the range β128 to 127, so == coincidentally works for small values. Never rely on this β always use .equals().
Performance
Autoboxing has a real runtime cost (allocation, dereferencing). For hot loops with primitives, prefer primitive types directly or use the primitive-specialised streams (IntStream, LongStream, DoubleStream).