library
beginnerAutoboxing & Unboxing Pitfalls
Know when Java automatically converts between primitives and wrappers, and the performance and correctness traps.
The compiler converts between primitives and wrappers for you. It inserts Integer.valueOf(n) to box and intValue() to unbox.
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
List<Integer> nums = new ArrayList<>();
nums.add(5); // becomes nums.add(Integer.valueOf(5))
int first = nums.get(0); // becomes nums.get(0).intValue()2
The null trap is the one that reaches production.
Map<String, Integer> counts = new HashMap<>();
int n = counts.get("missing"); // NullPointerException3
get returns null, and unboxing null throws. The stack trace points at the assignment, where there is
no visible method call to blame.
getnull
4
int n = counts.getOrDefault("missing", 0); // the fix5
The equality trap.
Integer a = 1000, b = 1000;
a == b; // false -- two objects
a.equals(b); // true6
Only -128 to 127 are cached, so == works for small values and silently stops working for large ones.
==
7
Mixing the two unboxes instead:
Integer a = 1000;
int b = 1000;
a == b; // true -- a is unboxed, values compared8
The performance trap.
Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) sum += i;9
sum is a Long, so every iteration unboxes, adds, and boxes a new object — a million allocations for a
loop that should allocate nothing. Declaring long sum fixes it.
sumLonglong sum
10
The ternary trap.
Integer x = null;
int y = flag ? x : 0; // NPE when flag is true11
Both branches must have one type, so the int branch promotes and the Integer branch unboxes.
intInteger
12
And overload resolution ignores boxing where it can. Given f(long) and f(Integer), f(5) picks
f(long), because widening is tried before boxing.
f(long)f(Integer)f(5)
13
What the interviewer is probing.1. "int n = map.get('missing') on a key that is absent — what happens?" Probing: the NPE that people meet in
production. Stalls: "It returns zero." Moves up: get returns null, unboxing null throws
NullPointerException, and the stack trace points at an assignment with no visible method call.
14
2. "Why is a loop with Long sum = 0L slow?" Probing: hidden allocation. Stalls: "It is the
same as long." Moves up: every iteration unboxes, adds and boxes a new Long, so a loop that should
allocate nothing allocates millions of objects.
15
3. "How should you compare two Integer values?" Probing: reference versus value equality.
Stalls: "With ==." Moves up: equals, or unbox one side — == compares references and only appears
to work inside the cache range.
16
4. "flag ? integerValue : intValue — what is the risk?" Probing: the ternary unboxing rule.
Stalls: "None." Moves up: both branches must have one type, so the Integer is unboxed and a null
throws, even on the branch that was not taken.