Q6: What are Autoboxing and Unboxing, and what performance pitfalls do they present?

  • Autoboxing: Automatic conversion of primitives to wrapper objects (int -> Integer).
  • Unboxing: Automatic conversion of wrapper objects to primitives (Integer -> int).
  • Pitfalls: Unboxing a null wrapper throws NullPointerException. Excessive autoboxing inside loops creates huge GC object pressure.
Autoboxing Performance Leak
// Bad: Autoboxes 1,000,000 Integer objects
Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) {
    sum += i; // Unboxes sum, adds i, autoboxes result to new Long object
}

// Good: Uses primitive long
long fastSum = 0L;
for (long i = 0; i < 1_000_000; i++) {
    fastSum += i;
}
💡 Using wrapper objects in accumulation loops allocates millions of redundant heap wrapper instances.
Key Takeaways
  • Autoboxing creates new object wrapper allocations implicitly.
  • Unboxing null wrapper references throws NullPointerException.
Knowledge Check

What error occurs when executing: Integer val = null; int num = val;