What are helpful NullPointerExceptions in Java 14+?

Since Java 14 (enabled by default from Java 15), a NullPointerException message names exactly which variable or method call was null. Before, the message was empty, and in a chained call such as order.getCustomer().getAddress().getCity() you couldn't tell which part failed.

Key Points: • The message says what could not be done and why, for example: Cannot invoke "String.length()" because "name" is null. • It is especially useful for chained calls and array access, where several values could be null. • It costs nothing in normal execution. The message is only computed when the exception's message is requested. • Local variable names appear only if the code was compiled with -g. Otherwise the message says something like "<local1>". • It complements, not replaces, null-safe design: Optional, validation and annotations such as @NonNull.

Code Example:

public class HelpfulNpeDemo {

    record Address(String city) {}
    record Customer(String name, Address address) {}
    record Order(Customer customer) {}

    public static void main(String[] args) {
        Order order = new Order(new Customer("Asha", null));
        try {
            System.out.println(order.customer().address().city().length());
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Cannot invoke "HelpfulNpeDemo$Address.city()" because the return value of "HelpfulNpeDemo$Customer.address()" is null

Good to Know: Use this to talk about production debugging: with helpful NPE messages, a single log line tells you which field was null, which shortens incident investigation. Then mention how you would prevent it, such as validating at the API boundary or returning Optional.

Interview Tip: A concise interview answer is:

"Since Java 14, a NullPointerException message says exactly which variable or method call was null, for example 'because the return value of address() is null'. It makes chained calls much easier to debug from a single log line, at no runtime cost."

Previous question: What is the Java 11 HttpClient, and how is it better than HttpURLConnection?

Next question: What are virtual threads in Java 21, and how are they different from platform threads?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions