Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Every way to handle a missing value

null and NullPointerException, guard clauses, getOrDefault, case null, Optional, and when to throw instead.

First decide what "missing" means here.

  • It must never be missing (a required argument) → check it at the boundary with a guard clause or Objects.requireNonNull, and fail fast with a clear message.
  • Missing has a sensible default (no count yet means 0) → map.getOrDefault(key, 0), or optional.orElse(...).
  • A lookup can legitimately find nothing → return Optional<T> so every caller must decide what to do; don't return null.
  • Missing is a real error the caller should handle → throw an exception that says what was missing.
  • A switch over an object that might be null → case null handles it explicitly instead of throwing.

Where null comes from

The value of a reference that points at no object.

A reference to no object at all.

The run-time error thrown when code calls a method on a null reference.

Example

String s = null; s.length();

What calling a method through null throws.

Why it happens and how to read the helpful message.

Keeping null out

A check at the top of a method that returns early for an input the rest can't handle.

Check the bad case at the top of a method and leave early.

Reject bad arguments in the constructor so an object is never half-valid.

Handle null as its own case instead of crashing.

Saying "maybe absent" in the type

get returns null for a missing key; getOrDefault doesn't.

A box that holds one value or is empty, returned when a result may be missing.

Example

findEmail(user).orElse("(none)")

A box that holds a value or is empty, so callers must decide.

Section

Optional

of, ofNullable, orElse, orElseGet, map and orElseThrow.