Fix NullPointerException in Java With Helpful Messages
Read the helpful NullPointerException message the JVM prints, find which expression was null and remove the cause instead of adding null checks everywhere.

java.lang.NullPointerException is the exception every Java developer meets first and keeps meeting. For most of Java's history its message was empty, and the stack trace told you which line threw but not which of the four things on that line was null. Since Java 15 (JEP 358) the JVM computes a helpful message that names exactly what was null and what the code tried to do with it. That one change turns most NPEs from a debugging session into a read. This post shows how to read the new messages with real output from running code, how to trace the null back to where it came from, why unboxing is a hidden dereference, which return values lie to you, what chains of calls hide, and how to make the next null fail earlier and louder. Every message below was produced by running the code on JDK 17; JDK 25 prints the same format.
How to read the message
The format is always "Cannot do X because Y is null". X is the operation the JVM attempted, and Y is the expression that turned out to be null. Run this and read the messages:
import java.util.*;
public class Npe {
record Address(String city) { }
record Customer(String name, Address address) { }
static Customer find(int id) {
return id == 1 ? new Customer("Ada", null) : null;
}
static void run(Runnable r) {
try {
r.run();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
run(() -> System.out.println(find(1).address().city().length()));
run(() -> System.out.println(find(2).name()));
run(() -> { Map<String, Integer> m = new HashMap<>(); int n = m.get("x"); });
run(() -> { int[] a = null; System.out.println(a[0]); });
run(() -> { String s = null; synchronized (s) { } });
run(() -> Objects.requireNonNull(null, "customer must not be null"));
}
}Cannot invoke "Npe$Address.city()" because the return value of "Npe$Customer.address()" is null
Cannot invoke "Npe$Customer.name()" because the return value of "Npe.find(int)" is null
Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
Cannot load from int array because "<local0>" is null
Cannot enter synchronized block because "<local0>" is null
customer must not be nullRead the first line left to right. The code called find(1).address().city().length(). The message says the JVM could not call city() on the Address, because address() on the Customer returned null. So the null is not in city, nor in length; it is the address of customer 1. The old message, java.lang.NullPointerException and a line number, would not have told you which of the three dereferences on that line failed.
Two details that help. The text <local0> appears instead of a variable name because the program was compiled without debug information. Compile with javac -g, or use Maven or Gradle, which include it by default, and the message names the real variable, for example because "customer" is null. And the message exists only for NPEs the JVM throws itself. One created with new NullPointerException() or thrown by Objects.requireNonNull carries whatever text you gave it, which is the last line above. You can read the full -XX:+ShowCodeDetailsInExceptionMessages behavior in JEP 358; it has been on by default since JDK 15.
Find the source of the null, not the use
The stack trace points at where the null was used. The fix usually belongs where it was produced, and the helpful message names the producer: "the return value of Npe.find(int)" means start at find. Ask three questions, in order.
- Can this null legitimately exist?
find(2)returns null for a missing customer. That is a valid state the caller forgot to handle. - If yes, handle it at the boundary. Return an
Optional, throw a specific exception, or return a documented default. - If no, it is a bug upstream. Find who passed null and fix that, and add a check so the next one fails at the source.
For case 1, make the absence part of the type:
static Optional<Customer> find(int id) {
return id == 1 ? Optional.of(new Customer("Ada", null)) : Optional.empty();
}
String name = find(2).map(Customer::name).orElseThrow(() -> new CustomerNotFound(2));The compiler now forces every caller to decide. For a method that must never receive null, check at the entry:
Customer(String name, Address address) {
this.name = Objects.requireNonNull(name, "name");
this.address = address; // null is allowed here, by design
}A message of name thrown at construction is far easier to trace than an NPE ten calls later.
Unboxing is a hidden dereference
A line with no method call and no dot can still throw. Assigning a boxed value to a primitive calls intValue(), longValue() or booleanValue() on it:
Map<String, Integer> stock = new HashMap<>();
int n = stock.get("A-100"); // NullPointerException: unboxing a missing keyCannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is nullThe message is the clue: any mention of intValue, longValue or booleanValue means an unboxing. Common sources are Map.get for a missing key, a nullable database column mapped to Integer and then used in arithmetic, a Boolean field on a JSON payload that the client omitted, and a ternary expression like flag ? 1 : nullableInteger, which unboxes the Integer even when you meant to return null. Fix it by choosing a default (stock.getOrDefault("A-100", 0)) or by checking first. When a column can be null, map it to a wrapper type on purpose and handle it in the mapper, not in the arithmetic.
Return values that cannot be null
Some APIs never return null by contract, and the habit of defending against them wastes effort. Others return null in ways that surprise people.
| Call | Returns null? |
|---|---|
Map.get(key) | Yes, when the key is absent (or maps to null) |
Optional.get() | Never; throws NoSuchElementException if empty |
String.valueOf(obj) | Never; returns the string "null" for a null obj |
List.of(...), Map.of(...) | Never; and they throw NPE if you pass or probe with null |
System.getenv("X"), System.getProperty("x") | Yes, when unset |
ResultSet.getString(col) | Yes, for SQL NULL |
Stream findFirst() | Never; returns an empty Optional |
The List.of row has a trap: List.of("a").contains(null) throws an NPE with no message, because the immutable collections reject null probes. If you check membership with data that may be null, use Objects.equals in a loop or an ArrayList. Inspecting a null-hostile collection with a null is an old source of bugs, as is passing null into Map.of.
Mark intent in your own APIs. Annotate parameters and returns with @Nullable from a library your tools understand (Spring's org.springframework.lang family or JSpecify), and let the IDE and static analysis find misuse before runtime. The language-level options available in current Java are summarized in the modern Java guide.
Chains that hide the null
A long chain of calls puts several possible nulls on one line, which is why the old message was useless. The helpful message names the failing call, but you can also remove the guesswork from the code:
// Hard to debug and to read
String city = order.getCustomer().getAddress().getCity().toUpperCase();
// Each step named; one null check, one place to report it
Customer customer = Objects.requireNonNull(order.getCustomer(), () -> "order " + order.getId() + " has no customer");
Address address = customer.getAddress();
String city = address == null ? "unknown" : address.getCity().toUpperCase();Break a chain when more than one link can be null. Use Optional chaining inside a method only when it reads better than the explicit version, and never as a field or a parameter type. In a debugger, a conditional breakpoint on the suspect variable stops at the exact moment it becomes null, which is faster than adding prints (see debugging in IntelliJ IDEA like a pro); see reading a Java stack trace correctly for matching the frames to your own code.
Where this does not apply
If the message reads Cannot read the array length because "<local1>" is null or mentions a field of this, the null is a field you forgot to initialize, usually in a constructor or a dependency injection failure; check that the framework created the object. If a NullPointerException carries only a custom message, it came from a library or your own requireNonNull, and the message is the diagnosis. If you see an NPE inside generated or proxied code (a name like $$SpringCGLIB$$), the target of the proxy was not set up; read the cause chain. And if the null is the real value of a legitimate domain concept, a missing middle name for example, represent it as Optional or an explicit state, and stop treating it as an error. The API reference for the helpers used here is the [Objects Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Objects.html).


