Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 null

When 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 unknown

A default value

Objects.requireNonNullElse() substitutes a fallback for null:

void main() {
    String nickname = null;
    IO.println("Hello, " + Objects.requireNonNullElse(nickname, "guest"));
}

Output:

Hello, guest

Optional

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
unknown

Checking 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 null

Common 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 null

Use getOrDefault("tea", 0) or keep the result in an Integer and check it.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.