NullPointerException
JavaFATALCommonReference

Null reference accessed

Quick Answer

Add a null check before dereferencing, or use Optional<T> to force explicit handling.

What this means

Thrown when code attempts to use null where an object is required — calling a method, accessing a field, or indexing an array on a null reference.

Why it happens
  1. 1Method called on a null object reference
  2. 2Returning null from a method whose caller assumes non-null

Fix

Guard with null check or Optional

Guard with null check or Optional
// null check
if (user != null) { user.getName(); }

// Optional
Optional.ofNullable(getUser())
        .map(User::getName)
        .orElse("anonymous");

Why this works

Optional forces callers to handle the absent-value case explicitly.

Code examples
Triggerjava
String s = null;
s.length(); // NullPointerException
Objects.requireNonNulljava
void process(String input) {
    Objects.requireNonNull(input, "input must not be null");
    System.out.println(input.length());
}
Optional chainjava
Optional.ofNullable(order)
    .map(Order::getCustomer)
    .map(Customer::getEmail)
    .orElse("no-email");
Sources
Official documentation ↗

Java SE Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Java errors