Quick revision
The short answer
The message comes from helpful NullPointerException messages, JEP 358, which the JVM has produced by default since Java 15: it describes exactly which expression was null and what the code tried to do with it. To fix the bug we decide whether a customer may have no email: if not, we validate at the input and fail fast with Objects.requireNonNull in the constructor; if so, we handle absence explicitly. To prevent it, lookups that may find nothing return Optional, and nullness annotations such as JSpecify, checked by NullAway, catch many cases at build time.
What to remember
In this answer, we saw that the message comes from helpful NullPointerException messages, JEP 358, on by default since Java 15, which name the failing operation and the null expression. We fixed the bug at its source by deciding whether email may be absent: validating input and failing fast with Objects.requireNonNull if not, and handling absence explicitly with Optional from the accessor if so. We prevent recurrences with Optional for lookups only, Bean Validation at the boundary, and JSpecify annotations checked by NullAway at build time.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The message comes from helpful NullPointerException messages, JEP 358, which the JVM has produced by default since Java 15: it describes exactly which expression was null and what the code tried to do with it. To fix the bug we decide whether a customer may have no email: if not, we validate at the input and fail fast with Objects.requireNonNull in the constructor; if so, we handle absence explicitly. To prevent it, lookups that may find nothing return Optional, and nullness annotations such as JSpecify, checked by NullAway, catch many cases at build time.
Why this question is asked
NullPointerException is the most common exception in Java production logs, and for most of Java's history its message said nothing at all, leaving us to guess which of several references on a line was null. Modern JVMs tell us precisely, and reading that message well is the first step of the fix. Interviewers ask this question because it moves from a simple fact, which feature produced the message, to the more important skill of fixing a null bug at its source and preventing the next one. In this answer, we will read the message, see how the JVM produces it, fix the bug properly rather than adding a null check where it crashed, and set up the habits and tooling that prevent it.
1Reading the Message
Let us take the message apart. Cannot invoke "String.length()" tells us the operation that failed: calling length() on a String. because the return value of "com.acme.Customer.getEmail()" is null tells us which expression produced the null: the result of getEmail() on a Customer. So the line looked something like customer.getEmail().length(), and the customer object itself was fine; its email was null.
Before Java 14, the same failure printed only java.lang.NullPointerException and the line number. On a line with customer.getEmail().length(), that left two candidates, customer and the email. With longer chains, such as order.getCustomer().getAddress().getCity(), there were three or four, and we had to reproduce the bug to find out which one.
2Which Feature Produced It
This is the helpful NullPointerException messages feature, introduced by JEP 358. It arrived in Java 14 behind the option -XX:+ShowCodeDetailsInExceptionMessages and has been enabled by default since Java 15, so every current JVM, including Java 21 and Java 25, produces these messages without any configuration.
The JVM computes the message lazily, only when getMessage() is first called, by analysing the bytecode of the method at the failing instruction to work out where the null came from. Local variable names appear in the message only if the class was compiled with debug information for them (javac -g); otherwise the message says something like "<local1>". Because the message is built lazily, the feature costs nothing for NullPointerExceptions that are never logged.
3Fixing the Bug at Its Source
The tempting fix is a null check on line 18. That stops the crash, but it hides the real question: is a customer without an email valid? The answer decides the fix, and it belongs to the business, not to the validator.
If every customer must have an email, the null is a data error that got in somewhere else, and the fix is at the boundary where customers are created: validate the request, and make the constructor refuse null so the failure happens immediately with a clear message, not three classes later. If a customer may have no email, for example for phone-only sign-ups, then absence is a normal state and every user of the field must handle it explicitly, which the type should make obvious.
Notice that the first case still throws a NullPointerException, but at the right place and with a message that names the field. The difference for debugging is enormous: the stack trace now points at the code that passed null, which is where the bug is.
On requests, Bean Validation does the same job one step earlier: @NotBlank on the email field of the request DTO makes Spring reject the request with a 400 before any of our code runs.
4Where Optional Fits, and Where It Does Not
Optional is designed as a return type for methods that may have no result, such as repository.findByEmail(email). It tells the caller, through the signature, to handle the empty case, and its methods such as map, orElse and orElseThrow make that handling concise.
It is not meant for fields, method parameters or collection elements. As a field it adds an object per instance and is not serializable; as a parameter it makes callers wrap values and still allows a null Optional; and a collection is better simply empty. That is why in the example above the field stays a plain, possibly null String, and only the accessor returns Optional.
5Preventing It at Build Time
Runtime checks catch nulls when they happen. Static analysis can catch many of them before the code runs. The approach is to annotate which references may be null and let a tool check every use. JSpecify is a standard set of nullness annotations agreed by several tool and library vendors: @NullMarked on a package or class says that everything is non-null unless marked, and @Nullable marks the exceptions. NullAway, an Error Prone plugin, then checks during compilation that nothing marked @Nullable is dereferenced without a check.
- Build timeJSpecify annotations, NullAway fails the build
- At the boundaryBean Validation on requests, NOT NULL in the schema
- At construction
Objects.requireNonNullwith a clear message - At runtimehelpful NPE messages point at the exact expression
4 steps in order. Play them, or step through them one at a time.
Each layer catches what the one before it missed.
6Follow-up questions
What changed in Spring Framework 7 about nullness annotations?
Spring Framework 7, the base of Spring Boot 4, moved its codebase to JSpecify annotations: the APIs are @NullMarked and use org.jspecify.annotations.Nullable, and Spring's own org.springframework.lang.Nullable and NonNull annotations are deprecated. This gives tools such as NullAway, IntelliJ and the Kotlin compiler precise nullness information for Spring's APIs, so Kotlin code sees Spring types as nullable or non-null correctly. Check your version for the migration details of your own code.
Can helpful NPE messages leak sensitive information?
They describe code, not data: method names, field names and local variable names, never the values. That is generally safe, but if method names themselves are considered sensitive, the feature can be turned off with -XX:-ShowCodeDetailsInExceptionMessages.
Should every method parameter be checked with requireNonNull?
Not every one. Constructors and public API entry points are the most valuable places, because they stop a null from being stored and causing trouble later. Inside a package that is annotated and checked by NullAway, the compiler already guarantees most of it.
7Conclusion
In this answer, we saw that the message comes from helpful NullPointerException messages, JEP 358, on by default since Java 15, which name the failing operation and the null expression. We fixed the bug at its source by deciding whether email may be absent: validating input and failing fast with Objects.requireNonNull if not, and handling absence explicitly with Optional from the accessor if so. We prevent recurrences with Optional for lookups only, Bean Validation at the boundary, and JSpecify annotations checked by NullAway at build time.
Open with
That message comes from helpful NullPointerException messages, JEP 358. It was added in Java 14 behind a flag and has been on by default since Java 15. The JVM analyses the bytecode at the failing instruction and says what operation failed, calling String.length(), and which expression was null, the return value of Customer.getEmail().
Then, if they want more
So the customer was fine; its email was null. For the fix, I would not just add a null check on that line, because the real question is whether a customer may have no email.
If email is required, the null got in somewhere else, so I validate at the boundary, for example @NotBlank on the request, and use Objects.requireNonNull in the Customer constructor with a clear message, so it fails where the bad data enters.
If email is optional, I make that visible: the accessor returns Optional of the email, and the validator handles the empty case explicitly. I use Optional for return values of lookups, not for fields or parameters.
To prevent this class of bug, I would annotate packages with JSpecify, NullMarked with Nullable where needed, and run NullAway in the build, so dereferencing a nullable value without a check fails compilation. Spring Framework 7 also moved to JSpecify annotations, so Spring's own APIs carry precise nullness information.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 15, Java 14, Java 21, Java 25
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A service logs: java.lang.NullPointerException: Cannot invoke "String.length()" because...": https://scrivio-interview-library.netlify.app/java/exceptions/8c8aa4c5f7/