How to avoid NullPointerException
Short answer
A NullPointerException happens when you call a method or access a field through a reference that is null. The message tells you what exactly was null:
String findCity(String user) {
return user.equals("anna") ? "Berlin" : null;
}
void main() {
String city = findCity("oleg");
IO.println(city.toUpperCase());
}Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "<local1>" is nullWhen you run a single file, local variable names in the message are replaced with <local1> and the like. In a project compiled with debug information you would see "city".
Checking for null
The most direct way is to check the value before using it:
void main() {
String city = null;
if (city != null) {
IO.println(city.toUpperCase());
} else {
IO.println("City unknown");
}
}Output:
City unknownA default value
Objects.requireNonNullElse() substitutes a fallback for null:
void main() {
String nickname = null;
IO.println("Hello, " + Objects.requireNonNullElse(nickname, "guest"));
}Output:
Hello, guestOptional
If a method may find nothing, let it return an Optional — then the calling code handles the empty result explicitly:
Optional<String> findCity(String user) {
return user.equals("anna") ? Optional.of("Berlin") : Optional.empty();
}
void main() {
IO.println(findCity("anna").map(String::toUpperCase).orElse("unknown"));
IO.println(findCity("oleg").map(String::toUpperCase).orElse("unknown"));
}Output:
BERLIN
unknownChecking arguments early
Objects.requireNonNull() throws right away with a clear message, instead of somewhere deep in the code:
record User(String name) {
User {
Objects.requireNonNull(name, "name must not be null");
}
}
void main() {
new User(null);
}Output:
Exception in thread "main" java.lang.NullPointerException: name must not be nullCommon mistake
Unboxing null into a primitive. This is also a NullPointerException, even though no method is called explicitly:
void main() {
Map<String, Integer> stock = new HashMap<>();
int count = stock.get("tea");
}Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is nullUse getOrDefault("tea", 0) or keep the result in an Integer and check it.
Functions used in this recipe
- Optional.ofNullable() — Wraps a value that may be `null` into an `Optional`.
- Optional.orElse() — Returns the value, or a fallback if there is none.
- Objects.requireNonNull() — Checks that a value is not null and throws NullPointerException with a clear message right away.