Why This Happens
Java auto-unboxes wrapper types like Integer to int automatically. When the wrapper is null, this unboxing triggers a NullPointerException. This is subtle because the code looks like a simple assignment, not a method call.
The Problem
Map<String, Integer> map = new HashMap<>();
int value = map.get("missing_key"); // NPE: unboxing null IntegerThe Fix
Map<String, Integer> map = new HashMap<>();
Integer value = map.get("missing_key");
if (value != null) {
int intValue = value;
}Step-by-Step Fix
- 1
Identify the unboxing
Look for assignments from wrapper types (Integer, Long, Boolean, Double) to primitive types (int, long, boolean, double).
- 2
Find the null source
Check if the wrapper value could be null, especially from Map.get(), database queries, or method return values.
- 3
Use wrapper type or default value
Use the wrapper type instead of the primitive, or provide a default with getOrDefault() or Optional.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free