Null contracts and fallback
What you will learn
A fallback is a policy decision: should missing data become a default, trigger another search, or stop the operation? Optional separates that choice from the initial lookup.
- Predict whether a fallback expression or supplier runs.
- Choose a default, secondary lookup or exception based on the domain.
- Enforce non-null boundaries using Objects utilities.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Count fallback evaluations
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { int[] calls = {0}; java.util.function.Supplier<String> fallback = () -> { calls[0]++; return "default"; }; var present = Optional.of("stored"); System.out.println(present.orElse(fallback.get()) + ":" + calls[0]); System.out.println(present.orElseGet(fallback) + ":" + calls[0]); System.out.println(Optional.<String>empty().orElseGet(fallback) + ":" + calls[0]); }}Expected output:
stored:1stored:1default:2The first expression runs even though its value is discarded. The lazy fallback runs only for the empty case.
Eager versus lazy
Java evaluates method arguments before entering the method. orElse(expensive()) calls expensive even if the Optional contains a value. orElseGet(() -> expensive()) runs the supplier only for absence. A method reference can express the same supplier. Use orElse for cheap constants; use orElseGet for work that should not run when unnecessary. A supplier expression itself is still evaluated as an argument; defer the work inside its body.
Choose the output shape
orElse and orElseGet return T, and may return null if the supplied fallback is null. Do not choose null if the caller expects a non-null result. or (Java 9) returns an Optional from a secondary lookup, evaluating its supplier only when needed; the returned Optional must not be null. orElseThrow() rejects absence with NoSuchElementException; the supplier overload lets you choose a domain-specific exception, including checked exceptions. Do not call get just to discover whether something exists.
Nullability is a boundary contract
Decide whether each input is required, optional or invalid. Objects.requireNonNull rejects invalid null input at entry and returns the original non-null reference. requireNonNullElse and requireNonNullElseGet (Java 9) guarantee a non-null result or throw; unlike Optional fallback methods, null cannot be the final value. A sentinel such as -1 works only if the domain excludes that value and every caller knows the convention. Document such a policy rather than silently mixing absence and invalid data.
Continue a secondary lookup
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,Integer> local = Map.of("A", 0); Map<String,Integer> backup = Map.of("A", 9, "B", 4); for (String id : List.of("A", "B", "C")) { var result = Optional.ofNullable(local.get(id)).or(() -> Optional.ofNullable(backup.get(id))); System.out.println(id + ":" + result.map(Object::toString).orElse("missing")); } }}Expected output:
A:0B:4C:missingA present zero wins over the backup. The final missing state remains explicit until formatting.
Require a known item
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { Map<String,Integer> stock = Map.of("A", 5); for (String sku : List.of("A", "B")) { try { int quantity = Optional.ofNullable(stock.get(sku)).orElseThrow(() -> new IllegalArgumentException("Unknown SKU: " + sku)); System.out.println(quantity); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } } }}Expected output:
5Unknown SKU: BThe required lookup refuses to invent stock for a missing SKU. The outer boundary reports the known failure.
Enforce non-null defaults
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { String label = Objects.requireNonNull("Bolt", "label"); System.out.println(label); System.out.println(Objects.requireNonNullElse(null, "unknown")); System.out.println(Objects.requireNonNullElseGet(null, () -> "generated")); System.out.println(Optional.<String>empty().orElse(null) == null); }}Expected output:
BoltunknowngeneratedtrueObjects defaults guarantee a non-null result or throw. Optional permits a null fallback, so the caller still owns that contract.
Common mistakes
Avoid orElse(loadFromNetwork()) when the lookup should avoid unnecessary work. Do not use orElse(0) if zero means an existing item with no stock. Do not use null as an Optional wrapper or return null from an or supplier. Avoid catching arbitrary RuntimeException and converting it to a default.
Practice
Simulate a cached price of 0 cents and a missing price. A supplier returns 250 cents and increments a counter. Use orElseGet and print price and cumulative calls for both cases.
Expected output:
0:0250:1Compare your answer with the manual practice criteria.
Official reading: Java SE 25 Optional · Objects. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Null contracts and fallback — knowledge check
Original Java Optional contract and boundary questions. Java 21-compatible scope.
With a present value, does orElse(build()) call build?
Which call defers work until absence?
Which method keeps the result Optional?
What happens if requireNonNullElse receives two null references?
When should missing inventory become zero?