Null Handling
in Java
Learn to handle null references deliberately and avoid the dreaded NullPointerException: the "billion-dollar mistake."
What Is null?
In Java, null is a special literal that means "no object." Any reference variable that has not been assigned to an actual object holds the value null by default.
Why null Matters
NullPointerException (NPE) is the most common runtime exception in Java. Tony Hoare, who invented null references, famously called it his "billion-dollar mistake."
Where null Comes From
The Golden Rule
The Null-Check Decision Flow
null vs. Empty
A common source of confusion: null and empty are fundamentally different. One means "nothing exists," the other means "something exists but contains nothing."
| null | Empty | |
|---|---|---|
| Meaning | No object at all | Object exists, but has no content |
| String example | null | "" |
| List example | null | Collections.emptyList() |
| .length() call | NPE crash! | Returns 0 |
| Safe to iterate? | No | Yes (0 iterations) |
Step-by-Step Null Safety
Example 1: Basic Null Check
int len = name.length(); // NPE if name is null!
if (name != null) {
int len = name.length();
System.out.println("Length: " + len);
} else {
System.out.println("Name not provided");
}
Example 2: Default Values
Instead of branching with if/else, assign a default value when the reference is null. This is shorter and often clearer.
String name = getUserName();
String display = (name != null) ? name : "Guest";
// Java 9+ Objects.requireNonNullElse
String display = Objects.requireNonNullElse(name, "Guest");
Example 3: Optional<T>
Optional is a container that may or may not hold a value. It forces the caller to explicitly handle the "empty" case, making null impossible to ignore.
public Optional<String> findEmail(int userId) {
String email = database.lookup(userId);
return Optional.ofNullable(email);
}
// Caller must handle both cases
String result = findEmail(42)
.orElse("no-reply@example.com");
Optional Chaining
Optional provides powerful methods to transform and chain operations without ever touching null directly.
getUser(id)
.map(User::getAddress) // User -> Address (or empty)
.map(Address::getCity) // Address -> String (or empty)
.filter(c -> !c.isEmpty());
String result = city.orElse("Unknown");
@Nullable and @NonNull
Annotations document intent at the API level. IDEs and static analysis tools use them to warn you at compile time about potential NPEs.
public class UserService {
// Tells callers: this might return null
@Nullable
public String findName(int id) { ... }
// Tells callers: this NEVER returns null
@NonNull
public String getDisplayName(int id) {
String name = findName(id);
return (name != null) ? name : "Anonymous";
}
}
Useful Objects Utilities
The java.util.Objects class provides several null-safe utilities that simplify common patterns.
Objects.requireNonNull(name, "name must not be null");
// Returns default if null
Objects.requireNonNullElse(name, "default");
// Null-safe equals (no NPE if either is null)
Objects.equals(a, b); // instead of a.equals(b)
// Null-safe toString
Objects.toString(obj, "null");
Common Mistakes
Summary of Strategies
| Strategy | When to Use | Example |
|---|---|---|
| Null check (if/else) | Quick guard for single variables | if (x != null) { ... } |
| Default value | When a sensible fallback exists | requireNonNullElse(x, "N/A") |
| Optional<T> | Method returns that may be absent | Optional.ofNullable(x) |
| Fail-fast | Constructor/public method params | Objects.requireNonNull(x) |
| Annotations | Documenting API contracts | @Nullable / @NonNull |
| Empty collections | Methods returning lists/sets | Collections.emptyList() |
Question 1 of 5
What happens when you call .length() on a null String reference in Java?
Question 2 of 5
Which of the following is the best way to compare a possibly-null String to a literal?
Question 3 of 5
A method that searches a database for a user might not find one. What should it return?
Question 4 of 5
What does Objects.requireNonNull(param, "msg") do when param is null?
Question 5 of 5
Which line of code will NOT throw a NullPointerException, even if list is null?