JAVA-230 · Lesson 5 of 12 · 21 min
Optional and avoiding null
▶ Video coming soon A video version of this lesson is on the way.
Wednesday, October 13, started with a crash report. Kofi had typed a part code with a lowercase letter into StockRoom's lookup screen, the lookup returned null, and the next line called .quantity() on it. "NullPointerException, line 88," Hamza read out. "The map had no entry, and nothing said it might not." Ingrid's answer was that the method's return type should have said so. That is what Optional is for. An Optional<T> is a small container that either holds one value or is empty, and returning it from a method tells every caller, in the type itself, that there might be no result and that they must decide what to do about it.
The trouble with null
Tony Hoare, who added null references to a language in 1965, later called them his billion-dollar mistake. The problem is not that "nothing" exists; a lookup for an unknown code genuinely has no answer. The problem is that a null looks exactly like a real object to the compiler, so nothing forces the caller to check, and the failure appears later, somewhere else, as a NullPointerException. Since Java 14, these exceptions have helpful messages that name what was null, which makes them easier to find, but finding a bug quickly is still worse than not writing it.
import java.util.*;
public class Main {
record Part(String code, int quantity) { }
static final Map<String, Part> PARTS = Map.of(
"TUBE-700x25", new Part("TUBE-700x25", 3),
"BELL", new Part("BELL", 25));
static Part find(String code) {
return PARTS.get(code); // null when the code is unknown
}
public static void main(String[] args) {
System.out.println("BELL: " + find("BELL").quantity());
System.out.println("tube-700x25: " + find("tube-700x25").quantity());
}
}What this code does
The first lookup finds BELL and prints 25, but the second uses a lowercase code, so Map.get returns null and calling quantity on it throws a NullPointerException. The helpful message says the return value of Main.find(String) is null, which points straight at the method that hid the missing case. Nothing in find's return type warned the caller that this could happen.
$ javac Main.java
$ java Main
BELL: 25
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Main$Part.quantity()" because the return value of "Main.find(String)" is null
at Main.main(Main.java:16)Making and reading an Optional
There are three ways to make one. Optional.of(value) wraps a value that must not be null; passing null throws at once, which is useful because the mistake shows up where it was made. Optional.ofNullable(value) wraps a value that may be null and gives an empty Optional if it is. Optional.empty() is the empty one. Many library methods already return Optional: findFirst, min and max on streams, for example, because an empty stream has no first element.
Reading the value safely means saying what happens when it is missing. orElse(default) returns the value or a default; orElseGet(supplier) does the same but only builds the default when needed, which matters when the default is expensive; orElseThrow() returns the value or throws NoSuchElementException, and orElseThrow(supplier) throws an exception you choose. ifPresent(consumer) runs code only when there is a value, and ifPresentOrElse adds the empty case. isPresent() and isEmpty() exist, but if you find yourself writing if (opt.isPresent()) opt.get(), the code has gone back to null-checking with extra steps.
import java.util.*;
public class Main {
record Part(String code, int quantity) { }
static final Map<String, Part> PARTS = Map.of(
"TUBE-700x25", new Part("TUBE-700x25", 3),
"BELL", new Part("BELL", 25));
static Optional<Part> find(String code) {
return Optional.ofNullable(PARTS.get(code));
}
public static void main(String[] args) {
Optional<Part> bell = find("BELL");
Optional<Part> unknown = find("tube-700x25");
System.out.println("BELL found? " + bell.isPresent() + ", unknown found? " + unknown.isPresent());
System.out.println("BELL quantity: " + bell.map(Part::quantity).orElse(0));
System.out.println("Unknown quantity: " + unknown.map(Part::quantity).orElse(0));
find("TUBE-700x25").ifPresentOrElse(
p -> System.out.println("Tubes on hand: " + p.quantity()),
() -> System.out.println("No such part"));
find("PEDAL-FLAT").ifPresentOrElse(
p -> System.out.println("Pedals on hand: " + p.quantity()),
() -> System.out.println("No such part: PEDAL-FLAT"));
try {
Part p = unknown.orElseThrow(() -> new IllegalArgumentException("unknown part code: tube-700x25"));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}BELL found? true, unknown found? false BELL quantity: 25 Unknown quantity: 0 Tubes on hand: 3 No such part: PEDAL-FLAT Rejected: unknown part code: tube-700x25
What this code does
find now returns an Optional, so the caller cannot use the part without choosing what happens when it is missing. map turns a found part into its quantity and leaves an empty Optional empty, and orElse supplies 0 in that case. ifPresentOrElse handles both outcomes in one call, and orElseThrow lets the program fail with a clear message of its own instead of a NullPointerException.
Chaining: map, flatMap and filter
Optional has the same style of methods as a stream with at most one element. map(f) applies f to the value if there is one. filter(test) keeps the value only if it passes. flatMap(f) is for a function that itself returns an Optional, so the result is not an Optional inside an Optional. Chaining these lets you follow a path through objects where any step might be missing, such as a booking that may have a customer who may have a phone number, without a ladder of null checks. or(supplier), added in Java 9, tries a second source when the first is empty, and stream() turns an Optional into a stream of zero or one elements, which is useful with flatMap on a stream.
import java.util.*;
public class Main {
record Customer(String name, Optional<String> phone) { }
record Booking(int number, String bike, Optional<Customer> customer) { }
static final List<Booking> BOOKINGS = List.of(
new Booking(1041, "CITY-2", Optional.of(new Customer("Dana Ortiz", Optional.of("614-555-0142")))),
new Booking(1042, "CARGO-1", Optional.of(new Customer("Sam Liu", Optional.empty()))),
new Booking(1043, "TANDEM-1", Optional.empty()));
static Optional<Booking> booking(int number) {
return BOOKINGS.stream().filter(b -> b.number() == number).findFirst();
}
static String phoneFor(int number) {
return booking(number)
.flatMap(Booking::customer)
.flatMap(Customer::phone)
.orElse("no phone on file");
}
public static void main(String[] args) {
for (int n : new int[] {1041, 1042, 1043, 1099}) {
System.out.println(n + ": " + phoneFor(n));
}
Optional<Booking> cargo = booking(1042).filter(b -> b.bike().startsWith("CARGO"));
System.out.println("1042 is a cargo booking: " + cargo.isPresent());
System.out.println("Fallback: " + booking(1099).or(() -> booking(1041)).map(Booking::bike).orElse("-"));
}
}1041: 614-555-0142 1042: no phone on file 1043: no phone on file 1099: no phone on file 1042 is a cargo booking: true Fallback: CITY-2
What this code does
Each step of phoneFor may find nothing: the booking may not exist, it may have no customer, or the customer may have no phone. flatMap passes an empty result straight through, so one orElse at the end covers every missing step for bookings 1042, 1043 and 1099. or tries a second lookup when the first is empty, which is how the fallback finds booking 1041's bike.
This example breaks a rule on purpose, to show flatMap: the records store Optional in their fields. The next section explains why real code should not.
Where Optional belongs, and where it does not
Optional was designed for one job: a return type for methods that may have no result. The Java designers, and most style guides, advise against using it elsewhere. As a field, it adds an object to every instance and is not serializable; store a nullable field and offer a getter that returns Optional instead. As a method parameter, it forces callers to wrap values and still lets them pass null for the Optional itself; overload the method or accept a nullable value and check it. In collections, an empty collection already says "nothing", so return List.of() rather than null or an Optional of a list. And never return null from a method declared to return Optional: that defeats the whole point.
| Use | Good practice |
|---|---|
| Method that may find nothing | Return Optional<T> |
| Method that returns a collection | Return an empty collection, never null or Optional |
| Field that may be missing | Keep a nullable field; expose an Optional getter |
| Parameter that may be missing | Overload the method, or accept null and check it |
| Primitive results | Use OptionalInt, OptionalLong or OptionalDouble |
| Getting the value | orElse, orElseGet, orElseThrow or ifPresent, not isPresent then get |
import java.util.*;
public class Main {
static final class Bike {
private final String code;
private final String lockCode; // may be null: not every bike has a lock yet
Bike(String code, String lockCode) { this.code = code; this.lockCode = lockCode; }
String code() { return code; }
Optional<String> lockCode() { return Optional.ofNullable(lockCode); }
}
static List<String> overdue(List<String> bikes, Set<String> late) {
return bikes.stream().filter(late::contains).toList(); // empty list, never null
}
public static void main(String[] args) {
Bike city = new Bike("CITY-2", "4471");
Bike tandem = new Bike("TANDEM-1", null);
System.out.println(city.code() + " lock: " + city.lockCode().orElse("none"));
System.out.println(tandem.code() + " lock: " + tandem.lockCode().orElse("none"));
List<String> none = overdue(List.of("CITY-1", "CITY-2"), Set.of());
System.out.println("Overdue bikes: " + none + ", size " + none.size());
OptionalInt longest = java.util.stream.IntStream.of(2, 7, 3).max();
System.out.println("Longest rental: " + longest.getAsInt() + " days");
System.out.println("Longest of none: " + java.util.stream.IntStream.empty().max().orElse(0));
}
}CITY-2 lock: 4471 TANDEM-1 lock: none Overdue bikes: [], size 0 Longest rental: 7 days Longest of none: 0
What this code does
The Bike class keeps lockCode as an ordinary field that may be null, and only its getter returns an Optional, which is the pattern the Java designers recommend. overdue returns an empty list when nothing is late, so callers can loop or check size without a special case. IntStream.max returns an OptionalInt, the primitive version, which avoids boxing.
Other defenses against null
Optional is one tool among several. Objects.requireNonNull(value, "message") at the start of a constructor or method rejects null early, close to the mistake, with your own message; records benefit from this in a compact constructor. Objects.requireNonNullElse(value, default) swaps in a default. Immutable collections from List.of and Map.of refuse null elements entirely, which turns a later surprise into an immediate error. Some teams also use annotations such as @Nullable from a checker library, so tools can warn about unchecked uses; Java itself has no built-in null-safety annotations yet.
import java.util.*;
public class Main {
record Part(String code, int quantity) {
Part {
Objects.requireNonNull(code, "code must not be null");
if (quantity < 0) throw new IllegalArgumentException("quantity cannot be negative: " + quantity);
}
}
public static void main(String[] args) {
System.out.println(new Part("BELL", 25));
try {
new Part(null, 3);
} catch (NullPointerException e) {
System.out.println("Rejected: " + e.getMessage());
}
String note = null;
System.out.println("Note: " + Objects.requireNonNullElse(note, "(none)"));
try {
List.of("BELL", null);
} catch (NullPointerException e) {
System.out.println("List.of refuses null elements");
}
}
}Part[code=BELL, quantity=25] Rejected: code must not be null Note: (none) List.of refuses null elements
What this code does
The compact constructor rejects a null code at the moment the record is created, with a message that says exactly what was wrong. requireNonNullElse replaces a missing note with a default text. List.of throws as soon as it is given a null element, so a missing value cannot slip into the collection and cause trouble much later.
Hamza changed StockRoom's lookup to return Optional<Part>, and the compiler immediately showed him the four places that used the result without thinking about the missing case. "That's the point," Ingrid said. "The type did the reviewing."
Try it yourself
Look up a price safely
priceOf returns a price from the map, or null. Change it to return Optional<Long>, then change main to print the price in cents or the text not stocked when there is no price.
The program should print BELL: 650 and HORN: not stocked.
import java.util.*;
public class Main {
static final Map<String, Long> PRICES = Map.of("BELL", 650L, "CHAIN-11", 2499L);
static Long priceOf(String code) {
return PRICES.get(code);
}
public static void main(String[] args) {
for (String code : List.of("BELL", "HORN")) {
System.out.println(code + ": " + priceOf(code));
}
}
}Try it yourself
The first overdue rental
Use a stream with filter and findFirst to find the first rental with more than 7 days out. Print First overdue: followed by its bike, or First overdue: none if there isn't one, using map and orElse.
Run it for both lists: the program should print First overdue: CARGO-1 and then First overdue: none.
import java.util.*;
public class Main {
record Rental(String bike, int daysOut) { }
static String firstOverdue(List<Rental> rentals) {
return "First overdue: ?";
}
public static void main(String[] args) {
System.out.println(firstOverdue(List.of(new Rental("CITY-1", 3), new Rental("CARGO-1", 9), new Rental("CITY-4", 12))));
System.out.println(firstOverdue(List.of(new Rental("CITY-2", 2))));
}
}Common mistakes
MistakeReturning null from a lookup method.
InsteadReturn Optional<T> so the type tells callers there may be no result.
MistakeWriting if (opt.isPresent()) opt.get().
InsteadUse map, orElse, orElseGet, orElseThrow or ifPresent.
MistakeUsing Optional for fields and parameters.
InsteadKeep it for return types; use a nullable field with an Optional getter.
MistakeReturning null or Optional for an empty collection.
InsteadReturn an empty collection such as List.of().
MistakeUsing orElse with an expensive default.
InsteadUse orElseGet, which builds the default only when it is needed.
Summary and key terms
- A null reference looks like a real object to the compiler, so forgetting to check it causes a NullPointerException later; since Java 14 these have helpful messages.
- Optional<T> is a container that holds one value or is empty, and it is meant as a return type for methods that may find nothing.
- Optional.of, ofNullable and empty create one; orElse, orElseGet, orElseThrow, ifPresent and ifPresentOrElse read it; map, flatMap, filter and or chain steps that may each find nothing.
- Stream methods such as findFirst and max already return Optional, and primitive streams return OptionalInt and its relatives.
- Do not use Optional for fields, parameters or collections, and never return null from a method that returns Optional.
- Objects.requireNonNull, requireNonNullElse and null-refusing collections such as List.of are further defenses.
- Optional
- A container that either holds one value or is empty, used as a return type.
- Optional.ofNullable
- Wraps a value that may be null, giving an empty Optional for null.
- orElse
- Returns the value, or a default when the Optional is empty.
- orElseGet
- Like orElse, but builds the default with a Supplier only when it is needed.
- orElseThrow
- Returns the value, or throws an exception when the Optional is empty.
- flatMap (Optional)
- Applies a function that returns an Optional, without nesting one Optional inside another.
- Helpful NullPointerException
- The Java 14 feature that names which expression was null.
- Objects.requireNonNull
- A check that throws NullPointerException with your message when a value is null.
- OptionalInt
- The primitive version of Optional for an int that may be missing.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does returning Optional<Part> help callers?
Show answer
The type tells them there may be no part, so they must handle the empty case.
What is the difference between orElse and orElseGet?
Show answer
orElseGet only builds the default when the Optional is empty.
Which method chains a step that itself returns an Optional?
Show answer
flatMap.
Should a method returning a list return Optional when there are no results?
Show answer
No; it should return an empty list.
Where should a record reject a null component?
Show answer
In its compact constructor, with Objects.requireNonNull.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.