<code>NullPointerException</code> in Java β Causes and Fixes
NullPointerException (NPE) is the most frequent runtime exception in Java. It's thrown whenever you try to use a reference that holds null: call a method on it, read a field, index an array, unbox it into a primitive, or throw it.
The five patterns that cause 95% of NPEs
// 1. Method call on null
String s = null;
s.length(); // NPE
// 2. Field access on null
User u = null;
u.name; // NPE
// 3. Array indexing on null
int[] a = null;
a[0] = 1; // NPE
// 4. Auto-unboxing null wrapper
Integer i = map.get("missing"); // null β map has no such key
int v = i; // NPE on unbox
// 5. Returning null from a method that autoboxes
int count = users.size() == 0 ? null : users.size(); // compiles, NPE if true branch runs
Helpful NPE messages (Java 14+)
Modern JVMs print the exact expression that was null:
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.length()" because "order.customer.name" is null
at com.example.Service.process(Service.java:42)
Enable with -XX:+ShowCodeDetailsInExceptionMessages (on by default since Java 15). Saves minutes of bisection.
The right fixes
1. Don't return null β use Optional
// β
public User findById(long id) {
return db.lookup(id); // might be null
}
// β
public Optional<User> findById(long id) {
return Optional.ofNullable(db.lookup(id));
}
// Caller is forced to handle the empty case:
service.findById(42).ifPresent(u -> send(u));
2. Fail fast at boundaries
public void register(User u, String email) {
this.user = Objects.requireNonNull(u, "user");
this.email = Objects.requireNonNull(email, "email");
...
}
3. Prefer collection factories over nullable returns
return matches.isEmpty() ? null : matches; // β callers must null-check
return matches; // β
empty list is a valid answer
4. Use Objects.equals for null-safe equality
Objects.equals(a, b); // handles a == null or b == null
5. Annotate nullability
Tools like Spotless, ErrorProne, NullAway, IntelliJ inspections enforce @Nullable / @NonNull annotations at compile time.
Common mistakes
- Catching NPE β it's a bug, not a recoverable condition. Fix the cause.
- Returning
nullfrom a public API β forces every caller to remember the null-check. ReturnOptionalor an empty collection. - Checking null after use β
s.length(); if (s != null)β the NPE already happened.
Related
Pillar: Java exceptions. Siblings: try/catch, IllegalArgumentException. Debug quickly with the Java Online Compiler.