0Pricing
Java Academy · Lesson

Autoboxing Pitfalls

Null unboxing and == traps.

Autoboxing Pitfalls is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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!");
        }
    }
}

Null in Arithmetic

The trap also strikes inside expressions. Adding a null wrapper unboxes it first, which throws before the math even runs.

public class Main {
    public static void main(String[] args) {
        Integer count = null;
        try {
            int total = count + 5;
            System.out.println(total);
        } catch (NullPointerException e) {
            System.out.println("Null in arithmetic!");
        }
    }
}

Guarding Against Null

Always check a wrapper for null before unboxing it, or provide a default value.

public class Main {
    public static void main(String[] args) {
        Integer maybe = null;
        int safe = (maybe != null) ? maybe : 0;
        System.out.println(safe);
    }
}

The == Cache Surprise

Integer.valueOf caches values from -128 to 127. So two boxed values in that range can share the same object, and == returns true.

public class Main {
    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        System.out.println(a == b);
    }
}

Outside the Cache

Above the cache range, each boxing creates a distinct object. Now == compares references and returns false even though the numbers are equal.

public class Main {
    public static void main(String[] args) {
        Integer a = 200;
        Integer b = 200;
        System.out.println(a == b);
    }
}

Always Use equals

Because == on wrappers compares object identity, you must use .equals() to compare the actual numeric values.

public class Main {
    public static void main(String[] args) {
        Integer a = 200;
        Integer b = 200;
        System.out.println(a.equals(b));
    }
}

Mixing == With a Primitive

If one side of == is a primitive, Java unboxes the wrapper, so the comparison is by value. This is reliable but can still throw if the wrapper is null.

public class Main {
    public static void main(String[] args) {
        Integer a = 200;
        int b = 200;
        System.out.println(a == b);
    }
}

Hidden Boxing in Loops

Declaring a loop accumulator as a wrapper causes a new object on every iteration. Below, using Long instead of long would box repeatedly. Prefer the primitive.

public class Main {
    public static void main(String[] args) {
        long sum = 0;
        for (int i = 0; i < 1000; i++) {
            sum += i;
        }
        System.out.println(sum);
    }
}

Map get Returns Null

A common real-world bug: Map.get returns null for a missing key. Unboxing that result into an int throws. Use getOrDefault instead.

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        int score = scores.getOrDefault("missing", 0);
        System.out.println(score);
    }
}

Staying Safe

Two habits prevent most autoboxing bugs: never unbox a value that might be null, and always compare wrapper values with .equals() rather than ==.

Quick Check

Test your awareness of autoboxing pitfalls.

Recap

You learned the main autoboxing pitfalls:

  • Unboxing a null wrapper throws a NullPointerException
  • Guard with a null check or a default value
  • == on wrappers compares references, with caching from -128 to 127
  • Always use .equals() for value comparison
  • Use getOrDefault to avoid null from map lookups

Frequently asked questions

Is the “Autoboxing Pitfalls” lesson free?

Yes — the full text of “Autoboxing Pitfalls” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Autoboxing Pitfalls”?

Null unboxing and == traps. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Autoboxing Pitfalls” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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