01 / 21

Null Handling
in Java

Learn to handle null references deliberately and avoid the dreaded NullPointerException: the "billion-dollar mistake."

Java

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.

name "Alice" String object age null Reference variables Heap memory

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."

✕ Runtime crash
NPE terminates your program immediately with no compile-time warning.
★ Silent bugs
Null can propagate through many methods before it finally crashes, far from the real cause.
✓ Preventable
With deliberate practices, every NPE in your code can be caught before it runs.

Where null Comes From

1
Uninitialized fields: Instance variables of object types default to null.
2
Method return values: Methods like Map.get() return null when a key is missing.
3
Explicit assignment: Setting a variable to null to indicate "no value."
4
External data: Parsing JSON, reading databases, or API responses may produce null.

The Golden Rule

Never call a method on a reference GOLDEN RULE you haven't verified as non-null. Check First if (obj != null) before using Default Value Provide a fallback if null Avoid null Return empty collections/Optionals

The Null-Check Decision Flow

Use a reference variable Could it be null? No Use it! Yes Avoidable? Yes Return empty No Guard with null check if (x != null) { ... }

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

1
Identify the source: Is this variable from user input, a method return, a database query, or a field?
2
Check the contract: Read the Javadoc. Does the method say it can return null?
3
Guard early: Place a null check at the earliest point. Do not let null propagate.
4
Choose a strategy: Return a default, throw an exception, or use Optional.
5
Document your intent: Use @Nullable or @NonNull annotations so others know.

Example 1: Basic Null Check

DANGEROUS CODE
String name = getUserName();
int len = name.length(); // NPE if name is null!
SAFE CODE
String name = getUserName();
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.

// Ternary operator approach
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.

// Method returns Optional instead of nullable
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.

Optional<String> city =
  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");
.map()
Transform the value if present; skip if empty.
.filter()
Keep value only if it matches a condition.
.orElse()
Provide a fallback default value.

@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.

import org.jetbrains.annotations.*;

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.

// Throws NPE with message if null (fail-fast)
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

✕ Calling .equals() on null
Writing str.equals("hello") will crash with an NPE if str is null. Instead, use Objects.equals(str, "hello") or put the literal first: "hello".equals(str).
✕ Catching NPE
Using try/catch(NullPointerException) to "handle" null is a code smell. Always check before, not after.
✕ Returning null from collections
Returning null instead of an empty list forces every caller to add null checks. Return Collections.emptyList() instead.

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?