java.lang.NullPointerException
java.lang.NullPointerException in Java means you attempted to invoke a method, access a field, or unbox an object reference that currently points to null. One of the most common runtime exceptions in Java.
How do I fix java.lang.NullPointerException?
To fix java.lang.NullPointerException in Java, locate the line causing the error and check the values right before it runs. Most occurrences happen because of unboxing a null wrapper object into a primitive. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does java.lang.NullPointerException mean?
Every non-primitive variable in Java is a reference. If a variable has not been instantiated or was explicitly assigned null, attempting to access its members throws NullPointerException (NPE) at runtime.
Why does java.lang.NullPointerException happen?
1. Unboxing a null wrapper object into a primitive
Automatic unboxing implicitly invokes .intValue() or .booleanValue() on the object, which throws NPE if the wrapper is null.
Breaks
Integer count = null;
int total = count + 1; // throws NullPointerException!Works
Integer count = null;
int total = (count != null ? count : 0) + 1;2. Comparing strings with .equals() on a null variable
Calling a.equals(b) when a is null throws NPE. Reverse the comparison to compare safely.
Breaks
String role = getRole(); // might be null
if (role.equals("ADMIN")) { ... }Works
if ("ADMIN".equals(role)) { ... } // safe even if role is nullHow to find it in your own code
Perform null checks before dereferencing, or use Optional<T> / Objects.requireNonNullElse(). Put constant literals on the left side of equals() calls (e.g. "EXPECTED".equals(str)). Check for null before allowing auto-unboxing to primitive types.
Try it: fix this bug
easyjava.lang.NullPointerException during auto-unboxing of Integer wrapper to primitive int
public class Main {
public static int parseIntegerScore(Integer score) {
// Auto-unboxing score to int calls score.intValue(), which throws NPE if score is null
int val = score;
return val;
}
public static void main(String[] args) {
System.out.println(parseIntegerScore(null));
}
}More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.