Sub topic 8
Unboxing null: the hidden NullPointerException
This chapter assumes you know Java's primitive types, basic class syntax, how == and equals behave on objects, and how to use List and Map with generics. It also assumes you have met autoboxing, where the compiler converts between int and Integer for you.
Why this failure is easy to miss
A primitive such as int always holds a value. A wrapper such as Integer is a reference type, so it can also hold null. Autoboxing hides the difference between the two. The line below looks like a plain assignment, but it is not:
int count = someInteger;The compiler turns it into a method call:
int count = someInteger.intValue();If someInteger is null, that call throws NullPointerException (NPE). The stack trace points at a line that has no visible method call and no visible dereference. That is why this bug is called hidden.
The basic failure
The most common source is Map.get. It returns null when the key is absent.
import java.util.HashMap;
import java.util.Map;
public class NullUnboxing {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 3);
int safe = stock.getOrDefault("pear", 0); // 0, no exception
System.out.println(safe);
int unsafe = stock.get("pear"); // get returns null, unboxing throws NullPointerException
System.out.println(unsafe);
}
}The first line prints 0. The second assignment fails, because stock.get("pear") returns null and the compiler inserts intValue() on it.
The message depends on your JDK. Modern JVMs have helpful NPE messages, which produce text like this:
Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is nullThe intValue() in that message is the only visible sign that unboxing was involved. Learn to recognize it.
Where the compiler inserts unboxing
Unboxing happens in more places than assignment. Any context that needs a primitive value from a wrapper expression triggers it. The table lists the common ones.
| Situation | Example | What is called |
|---|---|---|
| Assignment to a primitive | `int x = boxed;` | `boxed.intValue()` |
| Method argument that expects a primitive | `Math.abs(boxed)` | `boxed.intValue()` |
| Arithmetic | `boxed + 1` | `boxed.intValue()` |
| Numeric comparison with `<`, `>`, `<=`, `>=` | `boxed > 0` | `boxed.intValue()` |
| `==` where one side is primitive | `boxed == 5` | `boxed.intValue()` |
| Compound assignment or increment | `boxed++` | unbox, add, box |
| Condition | `if (flag)` with `Boolean flag` | `flag.booleanValue()` |
| `switch` on a wrapper | `switch (boxed) {...}` | `boxed.intValue()` |
| Return from a method with a primitive return type | `return boxed;` | `boxed.intValue()` |
Each of these throws an NPE when the wrapper is null.
The `==` case needs care
Comparing two wrappers with == compares references, and a null is fine there. Comparing a wrapper with a primitive unboxes the wrapper instead.
public class MixedEquality {
public static void main(String[] args) {
Integer a = null;
Integer b = null;
System.out.println(a == b); // true: reference comparison, no unboxing
int five = 5;
System.out.println(a == five); // NullPointerException: a is unboxed
}
}The first comparison prints true because both sides are references. The second throws, because one side is int and the compiler unboxes a to compare numbers.
The ternary operator trap
The conditional operator ? : is the least obvious source. When one branch is a primitive and the other is a wrapper, Java applies binary numeric promotion and the whole expression becomes a primitive. The wrapper branch is unboxed even if you only meant to return it as an object.
import java.util.Map;
public class TernaryTrap {
public static void main(String[] args) {
Map<String, Integer> prices = Map.of("tea", 3);
boolean useDefault = false;
// The type of the ternary is int. When the condition is false,
// prices.get("coffee") is null and is unboxed.
Integer price = useDefault ? 0 : prices.get("coffee");
System.out.println(price);
}
}The variable price is an Integer, so you might expect null to be stored safely. It is not. The expression useDefault ? 0 : prices.get("coffee") has type int. The null is unboxed before the result is boxed again, and the program throws on that line.
A fix is to make both branches the same wrapper type:
Integer price = useDefault ? Integer.valueOf(0) : prices.get("coffee");When both operands are Integer, no unboxing takes place and price can be null.
Spotting the hidden unboxing
The next diagram shows the path a value takes in int x = map.get(key).
The decision happens at the call to get, but the failure happens one step later, in the unboxing call. That gap is why the exception often appears far from the code that made the mistake, for example when a null is stored in a field and unboxed in a different method.
Other common sources of null wrappers
Maps are the most frequent source, but not the only one.
- Uninitialized wrapper fields. An
intfield defaults to0, but anIntegerfield defaults tonull. A class that switched frominttoIntegercan start failing in code that was never touched. - Database and JSON mapping. Libraries map a SQL
NULLor a missing JSON property tonullwhen the target type is a wrapper. Calls such asResultSet.getIntreturn0for SQLNULL, which hides the problem in another way, whilegetObjectreturnsnull. Optionaland streams.stream.max(...).get()returns the element, which may itself be anullwrapper if the source had nulls (streams fromList.ofdo not allow nulls, but a list built by hand can contain them).- Method returns. A method declared
Integer findScore()that returnsnullfor "not found" gives callers no warning at compile time. - Auto-unboxing in loops.
for (int n : listOfIntegers)unboxes each element, so onenullin the list ends the loop with an NPE.
import java.util.ArrayList;
import java.util.List;
public class NullInList {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>();
scores.add(10);
scores.add(null); // allowed: ArrayList accepts null
scores.add(30);
int total = 0;
for (int s : scores) { // second iteration: scores.get(1).intValue() throws
total += s;
}
System.out.println(total);
}
}The loop adds 10 and then throws on the second element.
Defensive patterns
You have four main options. Pick the one that fits what a missing value means in your code.
- Supply a default. Use
getOrDefaulton a map when a missing key has a sensible fallback. - Check first. Use
containsKeyor an explicit!= nulltest when a missing value needs different handling. - Use
Objects.requireNonNullElseto replace anullwrapper with a default, in any context. - Fail clearly. Use
Objects.requireNonNull(value, "message")at the boundary where the value enters, so the error names the real problem.
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class DefensiveUnboxing {
static Integer lookup(Map<String, Integer> m, String key) {
return m.get(key);
}
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 3);
int a = stock.getOrDefault("pear", 0);
System.out.println(a);
Integer pears = lookup(stock, "pear");
int b = (pears != null) ? pears : -1;
System.out.println(b);
int c = Objects.requireNonNullElse(lookup(stock, "pear"), 0);
System.out.println(c);
try {
int d = Objects.requireNonNull(lookup(stock, "pear"), "no stock entry for pear");
System.out.println(d);
} catch (NullPointerException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Running it prints 0, -1, 0, and then Caught: no stock entry for pear.
Be careful with getOrDefault. It returns the default only when the key is absent. If the key is present and mapped to null, it returns null, and unboxing that still throws. HashMap allows null values, so this can happen.
Prefer primitives where `null` has no meaning
The most reliable fix is to stop using a wrapper where null is not a valid state. Use int for a counter, a field, or a method return that always has a value. A primitive cannot be null, so this class of bug cannot occur. Keep wrappers for the cases that need them: generic type arguments, and values where "absent" is a real state. For the second case, OptionalInt or Optional<Integer> states the absence in the type and forces the caller to deal with it.
Reading an unboxing NPE
When you see an NPE and cannot find the dereference, use this checklist:
- Read the helpful message. Look for
intValue,longValue,doubleValue, orbooleanValue. - Find the expression named in the message, such as
Map.get(Object). - Check whether that expression can return
null. - Look at the line for implicit contexts: arithmetic, comparisons, ternaries,
forloops, and method calls that take a primitive.
Summary of the rules
- Unboxing a
nullwrapper throwsNullPointerException, and the throwing call (intValue()and friends) is not in your source. Map.getreturnsnullfor absent keys, which makes it the most common trigger.- A ternary with one primitive branch and one wrapper branch has a primitive type, so it unboxes.
Integer == Integercompares references and never unboxes.Integer == intunboxes.- Prefer primitives when
nullis meaningless, and handle absence explicitly when it is meaningful.
Exercise
The code below compiles. What happens when it runs, which line throws, and how would you change it so that total is 0 when the key is missing, without using getOrDefault?
Map<String, Integer> counts = new HashMap<>();
counts.put("a", 1);
boolean verbose = true;
Integer total = verbose ? counts.get("b") : 0;
Show answer
The ternary has one Integer branch and one int branch, so its type is int. With verbose true, counts.get("b") returns null, which is unboxed with intValue(). The Integer total = ... line throws a NullPointerException. To get 0 for a missing key, make both branches the same wrapper type and handle the null explicitly. For example: Integer value = counts.get("b"); Integer total = value != null ? value : Integer.valueOf(0);. Using Objects.requireNonNullElse(counts.get("b"), 0) also works.
Exercise
A HashMap<String, Integer> contains the entry "x" -> null. Does int n = map.getOrDefault("x", 5); give 5? Explain, and name one way to get 5.
Show answer
No. getOrDefault returns the default only when the key is absent. Here the key is present with a null value, so the call returns null, and unboxing it throws a NullPointerException. One way to get 5 is int n = Objects.requireNonNullElse(map.get("x"), 5);, which handles both a missing key and a null value.