Sub topic 8
Unboxing null: the hidden `NullPointerException`
What you should already know
This chapter assumes that you know Java primitive types such as int, wrapper classes such as Integer, and basic List and Map use with generics. You should also know that null means that a reference does not point to an object.
An int always contains a number. An Integer contains either an object holding a number or null. This difference matters whenever Java converts an Integer to an int.
How unboxing causes the exception
Unboxing is the automatic conversion from a wrapper object to its primitive value. For example:
Integer count = 12;
int total = count;The compiler treats the assignment approximately like this:
Integer count = 12;
int total = count.intValue();The intValue() method belongs to Integer. Calling an instance method requires an object. If count is null, Java cannot call intValue(), so it throws NullPointerException.
The dangerous part is that the conversion can be inserted into an expression where it is easy to miss.
Integer count = null;
// Java needs an int for the addition, so it tries count.intValue().
int total = count + 1;The exception occurs before the addition takes place.
The same problem can occur in comparisons, arithmetic, method calls, return statements, and conditions:
Integer value = null;
if (value < 10) { // unboxing
System.out.println("small");
}
int doubled = value * 2; // unboxingA common `Map` failure
A Map<String, Integer> uses Integer because generic type arguments must be reference types. Map.get returns null when a key is absent.
import java.util.HashMap;
import java.util.Map;
public class NullUnboxingExample {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 3);
int apples = stock.get("apple"); // Integer 3 is unboxed
System.out.println(apples);
try {
int pears = stock.get("pear"); // null is unboxed
System.out.println(pears);
} catch (NullPointerException exception) {
System.out.println("The key had no usable number");
}
int defaultPears = stock.getOrDefault("pear", 0);
System.out.println(defaultPears); // 0
}
}getOrDefault supplies a value when the key is absent. However, it does not replace a value that is explicitly stored as null:
stock.put("banana", null);
Integer bananas = stock.getOrDefault("banana", 0); // still nullIf a map may contain null values, check the result explicitly or prevent null values from entering the map.
Safe handling patterns
Choose a policy for missing values before converting a wrapper to a primitive.
| Situation | Safe approach |
|---|---|
| Missing value has a meaningful fallback | Use `getOrDefault` or an explicit null check |
| Missing value is invalid | Throw a clear exception with `Objects.requireNonNull` |
| Absence has meaning | Keep the value as `Integer` and test for `null` |
An explicit check is often the clearest solution:
Integer quantity = stock.get("pear");
int safeQuantity;
if (quantity == null) {
safeQuantity = 0;
} else {
safeQuantity = quantity;
}You can also use a conditional expression:
int safeQuantity = quantity == null ? 0 : quantity;Do not write the conversion before the check:
int unsafeQuantity = quantity; // too early: unboxing may throwFinding hidden unboxing
When debugging, inspect expressions involving wrappers. These forms commonly unbox:
- Assigning an
Integerto anint - Passing an
Integerto a method that requiresint - Applying arithmetic such as
+,-,*, or/ - Comparing a wrapper with a primitive
- Returning a wrapper from a method whose return type is primitive
- Using a wrapper in a condition that requires a boolean value
Java does not convert null into a default number. A missing Integer is not automatically treated as zero.
The conversion path
Exercise
Exercise
What is wrong with int score = scores.get("Ada");, and how can you make it safe when a missing score should mean zero?
Show answer
Map.get returns an Integer, and it returns null when "Ada" is absent. Assigning that result to int causes unboxing and throws NullPointerException. Use int score = scores.getOrDefault("Ada", 0);, provided the map does not store explicit null values.