0Pricing
Java Academy · Lesson

Autoboxing Pitfalls

Null unboxing and == traps.

Convenience Has Traps

Autoboxing makes code cleaner, but it hides conversions that can cause surprising bugs. The two biggest traps are null unboxing and identity comparison with ==.

This lesson shows how to avoid both.

The Null Unboxing Trap

If a wrapper holds null and you unbox it to a primitive, Java throws a NullPointerException.

This is easy to miss because the code looks like a simple assignment.

public class Main {
    public static void main(String[] args) {
        Integer maybe = null;
        try {
            int value = maybe;
            System.out.println(value);
        } catch (NullPointerException e) {
            System.out.println("Cannot unbox null!");
        }
    }
}

All lessons in this course

  1. Primitive vs Wrapper Types
  2. Autoboxing and Unboxing
  3. Parsing and Valueof
  4. Autoboxing Pitfalls
← Back to Java Academy