library
beginnerAutoboxing & Unboxing Pitfalls
Know when Java automatically converts between primitives and wrappers, and the performance and correctness traps.
Autoboxing (primitive → wrapper) and unboxing (wrapper → primitive) were introduced in Java 5 to reduce boilerplate. The compiler inserts Integer.valueOf(n) for boxing and intValue() for unboxing automatically.
Autoboxing = an invisible assistant wrapping your groceries (convenient but slow if you have 10,000 items). Unboxing = unwrapping — but if the box is empty (null), the assistant drops everything.
Key Concepts
1
Performance trap: each autobox allocates an object (unless cached). In a loop adding ints to a List<Integer>, millions of tiny Integer objects are created and immediately become garbage. Use IntStream or primitive arrays when performance matters.
2
Equality trap: == on two Integer objects compares references, not values (except for cached range -128..127). Always use .equals() for wrapper comparison. But == between int and Integer triggers unboxing, so it compares values.
3
Null trap: unboxing a null wrapper throws NullPointerException. This is common when a method returns Integer and the caller assigns to int, or when using Map.get() which returns null for missing keys.
4
Overload resolution trap: autoboxing has lower priority than widening. Given print(long) and print(Integer), calling print(5) picks print(long) (widening int→long beats boxing int→Integer).
5
Ternary trap: condition ? Integer : int forces unboxing of the Integer branch. If it's null, NPE.