#null and NullPointerException
AddedEvery reference variable in Java (anything that isn't one of the eight primitives like int or boolean) can hold null: "no object here". Call a method on it and you get a NullPointerException (NPE), still the most common exception in Java code. Tony Hoare, who invented null references in 1965, called them his "billion-dollar mistake".
If you come from TypeScript with strictNullChecks, this is the biggest culture shock. In TS, string and string | null are different types and the compiler stops you calling .toUpperCase() on something that might be null. Java's type system doesn't track null at all: a String variable may hold a string or null, and the compiler can't tell you which. The mental model: every reference in Java is TypeScript's T | null, with the checks turned off.
What has improved is the error. Since Java 14, an NPE says exactly which reference was null, instead of just a line number. On a line like c.address().city().toUpperCase() that used to mean guessing between three candidates.
record Address(String city) {}
record Customer(String name, Address address) {}
void main() {
var customers = List.of(
new Customer("Rohit", new Address("Toronto")),
new Customer("Ana", null));
for (var c : customers) {
IO.println(c.name() + " lives in " + c.address().city().toUpperCase());
}
}$ java Npe.java
Rohit lives in TORONTO
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Npe$Address.city()" because the return value of "Npe$Customer.address()" is null
at Npe.main(Npe.java:9)- Two records (chapter 03) hold the data: a
Customerhas a name and anAddress. Ana's address isnull, which the compiler happily accepts. - For Rohit the chain works:
c.address()is anAddress,.city()is"Toronto",.toUpperCase()givesTORONTO. - For Ana,
c.address()returnsnull, and calling.city()on it throws. The message names the culprit:Cannot invoke "Npe$Address.city()" because the return value of "Npe$Customer.address()" is null. (Npe$Addressis the record's real name: in a compact source file your types are nested inside a class named after the file.) - Nothing catches the exception, so the program stops at
Npe.java:9; anything after it in the loop never runs. - In TypeScript with strict null checks,
address: Address | nullwould have refused to compilec.address.city. In Java the same mistake compiles and fails at run time, which is why the habits below matter.
An NPE deep inside a method is hard to trace back to whoever passed the null. The usual defence is to reject null at the boundary: in constructors and public methods, check the arguments and fail immediately with a clear message. Objects.requireNonNull does that in one line, and a record's compact constructor is the natural place for it.
import java.util.Objects;
record Customer(String name, String email) {
Customer {
Objects.requireNonNull(name, "name is required");
Objects.requireNonNull(email, "email is required");
}
}
void main() {
IO.println(new Customer("Rohit", "rohit@example.com"));
IO.println(new Customer("Ana", null));
}$ java Fail.java
Customer[name=Rohit, email=rohit@example.com]
Exception in thread "main" java.lang.NullPointerException: email is required
at java.base/java.util.Objects.requireNonNull(Objects.java:246)
at Fail$Customer.<init>(Fail.java:6)
at Fail.main(Fail.java:12)Customer { … }with no parameter list is a compact constructor: it runs before the record's fields are assigned, so it's where you validate.- The first customer passes both checks and prints with the record's generated
toString():Customer[name=Rohit, email=rohit@example.com]. - The second has a
nullemail.requireNonNullthrows an NPE with your message,email is required, at the moment the bad object is created, not later when someone reads the email. - The stack trace shows where the bad value came from: the constructor (
Fail.java:6) called frommainat line 12. That's the point: the error points at the caller who passed the null.
Because the compiler doesn't track null, teams add annotations that tools can check: @Nullable on things that may be null, and a default of "not null" for everything else. The standard set now is JSpecify (org.jspecify.annotations), and Spring Framework 7 / Spring Boot 4 annotate their whole API with it, so IntelliJ and checkers like NullAway warn when you pass a possibly-null value where Spring expects non-null. It's not built into javac: without a checker, the annotations are only documentation. You'll see them in Spring code from chapter 12 on.