Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

NullPointerException

Thrown when a method or field is accessed through a `null` reference.

Available since: Java 1.0

Syntax

public class NullPointerException extends RuntimeException

Examples

The detailed message shows what exactly was null:

record User(String name, String email) {}
 
void main() {
    var user = new User("Anna", null);
    try {
        IO.println(user.email().length());
    } catch (NullPointerException e) {
        IO.println(e.getMessage());
    }
}

Output:

Cannot invoke "String.length()" because the return value of "Main$User.email()" is null

Checking up front with Objects.requireNonNull():

void greet(String name) {
    Objects.requireNonNull(name, "name must not be null");
    IO.println("Hello, " + name);
}
 
void main() {
    greet("Oleg");
    try {
        greet(null);
    } catch (NullPointerException e) {
        IO.println(e.getMessage());
    }
}

Output:

Hello, Oleg
name must not be null

Notes

Since Java 14 the message describes in detail which call failed and why. Typical causes: an uninitialized field, the result of Map.get() for a missing key, unboxing null into an int. Protection: null checks, Optional, getOrDefault(), Objects.requireNonNull() at the start of a method.

See also

  • Optional — A container that either holds a value or is empty — a replacement for returning `null`.
  • Optional.ofNullable() — Wraps a value that may be `null` into an `Optional`.
  • Map.get() — Returns the value for a key, or `null`.
  • RuntimeException — The base class of unchecked exceptions — bugs in program logic.

In the tutorial

  • What exceptions are — Exceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.

Thanks for reading!

Donate to the site — we work hard for you.