A NullPointerException means the code used a reference that pointed at nothing: called a method on it, read a field, indexed it as an array, or unboxed it into a primitive. Since Java 14 the message says precisely which expression was null, which turns the most infamous error in the language into one of the easier ones to fix. The remaining work is finding why it was null, and that is one of five situations.
Reading the message#
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.length()" because "name" is null
at Main.greet(Main.java:14)
at Main.main(Main.java:6)
Two parts. What was attempted: invoking String.length(). What was null: the local variable name. For fields it says "this.user" is null; for method results, the return value of "Repo.find(int)" is null; for array elements, "items[3]" is null. The stack trace gives the line. You now know the null value; the question is where it came from.
If you see a bare NullPointerException with no detail, you are on a Java older than 14, or running with helpful messages disabled. Upgrade; the detail is worth it.
Cause 1: a field never assigned#
class Cart {
private List<Item> items; // null until something assigns it
void add(Item i) { items.add(i); } // NPE: "this.items" is null
}
Reference fields default to null. Initialise at declaration, private final List<Item> items = new ArrayList<>();, or in the constructor. Making it final forces the compiler to check that every constructor assigns it.
Cause 2: a lookup that found nothing#
Map<String, User> users = ...;
users.get("bob").getEmail(); // NPE if "bob" is not in the map
Map.get, a repository’s findById, System.getenv, getResource: all return null for “not there”. Check, or use a form that handles absence:
User u = users.get("bob");
if (u != null) { ... }
users.getOrDefault("bob", User.ANONYMOUS).getEmail();
Optional.ofNullable(users.get("bob")).map(User::getEmail).orElse("none");
Cause 3: a method that returned null#
Cannot invoke "String.trim()" because the return value of "Config.get(String)" is null
The message names the method. Open it and see when it returns null. Then decide at the call site whether null is a legitimate outcome to handle, or a bug in the callee to fix. Methods that return collections should return empty collections, never null; that single rule removes a large share of NPEs.
Cause 4: a chain#
order.getCustomer().getAddress().getCity().toUpperCase();
Any link can be null, and before Java 14 you could not tell which. Now the message says, for example, because the return value of "Customer.getAddress()" is null. Break the chain where absence is possible, or use Optional to express it:
String city = Optional.ofNullable(order.getCustomer())
.map(Customer::getAddress)
.map(Address::getCity)
.map(String::toUpperCase)
.orElse("UNKNOWN");
Cause 5: unboxing#
Map<String, Integer> counts = new HashMap<>();
int n = counts.get("x"); // NPE: unboxing null Integer to int
Assigning an Integer that is null to an int calls intValue() on null. This one surprises people because no dot is visible. Use getOrDefault("x", 0), or keep the wrapper type and check.
The same applies to Boolean in an if, Long in arithmetic, and any wrapper compared with == to a primitive.
Other places it hides#
- An array allocated but its elements not:
new User[10]holds ten nulls. - A
switchon a null String or enum, before Java 21’s null case support. - Synchronising on a null lock object.
- Dependency injection that did not happen: a field annotated for injection but the class was created with
newrather than by the framework.
Preventing them#
- Do not return null from your own methods. Return an empty collection, an
Optional, a sentinel object, or throw. - Fail fast at boundaries:
Objects.requireNonNull(param, "param must not be null")in constructors and public methods, so the NPE happens where the bad value enters, not three calls later. - Use Optional for return values that may be absent, and not for fields or parameters.
- Initialise collections at declaration, and make fields final where possible.
- Nullness annotations,
@Nullableand@NonNull, with a checker in the build, turn many of these into compile-time warnings.
Questions people ask#
Why does Java have null at all?
Historical design; its inventor later called it a mistake. Records, Optional and nullness annotations are the language’s gradual answer.
Is Optional the fix for everything?
No. It is for return values that may legitimately be absent. Using it for fields and parameters adds noise without adding safety.
What is the difference between NPE and NoSuchElementException?
NoSuchElementException comes from Optional.get() or an iterator with nothing left. It is the Optional way of saying the same thing, and the fix is the same: check before you get.
Can Kotlin or other JVM languages avoid this?
Kotlin’s type system distinguishes nullable from non-null types and refuses to compile most NPEs. Java gets part of the way with annotations and a checker.
Where to go next#
- “cannot find symbol” — the compile-time counterpart.
- Records vs classes — immutable data with fewer nulls.
- How to read a stack trace — the lines under the message.