Hiprup

What is autoboxing and unboxing in Java?

Autoboxing is the automatic conversion between primitives (int, double) and their corresponding wrapper classes (Integer, Double). Unboxing is the reverse.

  • Why — collections and generics work only with objects, not primitives.

  • Compiler magic — the compiler inserts Integer.valueOf() / intValue() calls.

  • CachingInteger.valueOf(-128..127) returns cached instances; == can compare equal for those but not larger values.

  • Pitfalls — performance overhead in loops; NullPointerException if you unbox a null wrapper.

// Autoboxing (primitive -> wrapper)
Integer num = 42;              // int autoboxed to Integer
List<Integer> list = new ArrayList<>();
list.add(10);                   // int autoboxed to Integer

// Unboxing (wrapper -> primitive)
int value = num;                // Integer unboxed to int
int sum = num + 10;             // num unboxed, added, result is int

// NullPointerException risk
Integer nullInt = null;
int danger = nullInt;           // NPE! Unboxing null

// Performance trap
Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) {
    sum += i;  // Unbox sum, add, autobox result — creates 1M objects!
}
// Fix: use primitive long
long sum = 0L; // No boxing, much faster

Autoboxing converts int 42 to Integer automatically. Unboxing converts Integer back to int.

The null unboxing shows the NPE risk. The performance trap creates 1 million temporary Long objects because sum is a wrapper — using primitive long avoids all boxing.

The performance trap in loops is the key practical point. Know the NPE risk from unboxing null.

The Integer cache (-128 to 127) is a related topic. Recommend primitives for performance, wrappers for nullability and collections.

What is autoboxing and unboxing in Java? | Hiprup