Course outline

Java / Intermediate / Lesson 14

Optional values and explicit absence

Represent expected absence and fallback policies with Java Optional.

About 19 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish absence from a present zero.
  • Choose and test a fallback policy.
  • Distinguish presence, absence, and failure and design an explicit fallback policy.
  • Trace orElse and orElseGet evaluation and ownership of a contained value.

Model expected absence

A lookup can complete successfully without finding a value. Optional makes that absence visible in the return type instead of reserving an ordinary value as a sentinel. Decide whether absence is expected or represents a failure before choosing the contract. An empty Optional does not explain why a value is missing; preserve a separate error result when callers need that information.

Distinguish present and empty

Optional.of requires a non-null value, while Optional.empty represents absence. The example returns a present zero for one key and an empty result for another. Zero remains a real value and is not confused with missing data. A caller can check presence or transform a present value; avoid calling get without establishing that a value exists.

java Optional result
import java.util.Optional;

public class Main {
    static Optional<Integer> count(String key) {
        return key.equals("empty") ? Optional.of(0) : Optional.empty();
    }
    public static void main(String[] args) {
        count("empty").ifPresent(System.out::println);
    }
}
Expected output
0

The present zero is printed.

Choose a fallback

orElse supplies a fallback for an empty Optional. The example contrasts absence with a present zero. Choose a fallback only when the domain contract permits it, and understand that Java evaluates method arguments before the call. If constructing a fallback is expensive or has side effects, use an appropriate lazy alternative such as orElseGet and test when its supplier runs.

java Optional result
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Optional<Integer> missing = Optional.empty();
        Optional<Integer> zero = Optional.of(0);
        System.out.println(missing.orElse(5) + " " + zero.orElse(5));
    }
}
Expected output
5 0

Only the empty Optional uses the fallback.

Understand the contained reference

An Optional is a wrapper around a reference; it does not make the contained object deeply immutable or thread-safe. Clarify whether a caller may mutate a returned object and whether it shares state with the producer. Avoid using Optional as a substitute for input validation or detailed failure reporting. A documented API should define which conditions produce absence.

Test distinct outcomes

Test an empty result, a present ordinary value, and a present boundary value such as zero. Verify that a fallback is applied only where permitted and that its lazy supplier is not called for a present value when that matters. If failures are separate from absence, exercise those paths independently. A nonzero success case alone cannot distinguish absence from a sentinel design.

Name the meaning of absence

Optional is a value-based container for either one non-null reference or no value. A method returning Optional should define exactly what empty means: a successful lookup without a match is one possible meaning, while a timeout or malformed response is a different outcome unless the domain explicitly says otherwise. Do not use null as the Optional object itself; that creates a second, undocumented absence channel and forces callers to check the wrapper before they can use its contract. A present zero, false, or empty string is still present.

Choose the result model from what callers need to decide. If callers must distinguish not found, unauthorized, and unavailable, a single empty Optional cannot carry all three reasons. Use documented failures or a suitable result type for those cases and reserve empty for the stated successful absence. Avoid sentinel values that overlap valid data. Test present ordinary values, present boundary values, and empty independently; a test with only a positive number cannot reveal confusion between zero and missing.

Transform without losing meaning

Optional.of rejects null, while ofNullable converts a nullable reference to empty or a present Optional. Use the latter only when null legitimately means absence at that boundary. map transforms a present value and treats a null mapper result as empty; that can hide a defective mapper if null is not a valid domain outcome. flatMap is intended for a mapper that already returns a non-null Optional and avoids an extra Optional layer. filter can turn a present value into empty when the predicate fails, so its reason for absence should match the API contract.

A caller may use isPresent and a branch, ifPresentOrElse, orElseThrow, or another operation appropriate to the required outcome. Calling get on empty throws NoSuchElementException, so an unconditional get merely moves the missing-value decision to an accidental exception. Do not use an empty result to represent invalid data unless that loss of detail is explicitly acceptable. Test both branches and the mapper’s input and output contract, including a mapper that returns null if the design must detect it.

Make fallback evaluation deliberate

Java evaluates method argument expressions before invoking the method. Therefore optional.orElse(buildFallback()) calls buildFallback even when the Optional is present; the present value is returned, but the fallback’s cost or side effect has already occurred. orElseGet(() -> buildFallback()) passes a supplier and invokes it only when the Optional is empty. Both choices still require a documented fallback value and a policy for any exception raised while building it.

Do not choose a fallback solely to remove a branch from code. A missing configuration value might permit a documented default, while a missing authorization record or failed payment lookup should not silently become a permissive value. An eager fallback that throws can prevent a present value from being returned because the argument fails before orElse executes. Test present and empty cases with a synthetic call counter, and check that a required effect is not accidentally invoked on the present path.

Specify ownership of a contained object

Optional does not make its contained object immutable, independent, or thread-safe. Optional.of(list) can hold a reference to a mutable list shared with the producer. A caller that obtains the list may observe or cause changes according to the list’s actual ownership policy. If the API promises an independent result, create an appropriate defensive copy; if it promises deep independence, also address mutable elements. A wrapper’s presence semantics and the contained object’s lifetime and mutation rules are separate questions.

Optional is a value-based class: do not use its object identity as a synchronization mechanism or assume a particular empty instance is a singleton. Compare the intended values rather than relying on == between wrappers. A stream obtained from an Optional contains zero or one element, which can simplify composition, but the surrounding stream’s resource and ordering contract still matters. Test mutation through the original source and through the returned value when independence is promised, and document any deliberate sharing.

Test outcome, effects, and limits

A useful test matrix includes present zero, a present nonzero value, empty, and operational failure. Assert the returned value or explicit failure, whether a fallback supplier ran, and any state that must remain unchanged. For chained operations, test a present value that passes a filter, one that fails, and an initially empty value. Use controlled fake collaborators to make calls observable, but do not claim that a fake proves network availability or production storage behavior.

The worked examples below are Java 17 illustrative fragments and synthetic traces. They require surrounding imports and context, and they are not presented as executed programs. When running a complete test, record the actual compiler, runtime, input, and outcome. Keep failure information in an appropriately restricted diagnostic boundary while testing that public messages do not expose secrets. Structural checks can confirm the presence of fields and cases, but independent review is still needed to evaluate the meaning and derivation of each case.

20 worked examples

1. Explicit absence trace 1

Problem: Check whether zero is present.

  1. The Optional contains the non-null Integer value zero.
  2. Presence depends on containment, not whether the value is nonzero.
java Illustrative fragment
Optional<Integer> x=Optional.of(0); boolean p=x.isPresent();

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: p=true

Why this result follows: Zero is a valid present value.

2. Explicit absence trace 2

Problem: Check an explicitly empty result.

  1. The factory creates an Optional without a value.
  2. isPresent reports that no value is contained.
java Illustrative fragment
Optional<Integer> x=Optional.empty(); boolean p=x.isPresent();

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: p=false

Why this result follows: Empty is distinct from a present zero.

3. Explicit absence trace 3

Problem: Check of with a null value.

  1. Optional.of requires a non-null argument.
  2. The supplied reference is null. Use ofNullable only when null legitimately means absence.
java Illustrative fragment
Optional<String> x=Optional.of(null);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: NullPointerException

Why this result follows: Use ofNullable only when null legitimately means absence.

4. Explicit absence trace 4

Problem: Convert a nullable reference at a defined boundary.

  1. The supplied reference is null.
  2. ofNullable returns an empty Optional for that input.
java Illustrative fragment
Optional<String> x=Optional.ofNullable(null);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: x.isEmpty()=true

Why this result follows: The wrapper itself is not null.

5. Explicit absence trace 5

Problem: Evaluate fallback for a present zero.

  1. The Optional contains zero.
  2. orElse returns the contained value rather than the alternative.
java Illustrative fragment
int n=Optional.of(0).orElse(5);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: n=0

Why this result follows: Zero is not treated as absence.

6. Explicit absence trace 6

Problem: Evaluate fallback for an empty result.

  1. The Optional has no contained value.
  2. orElse selects the supplied alternative 5.
java Illustrative fragment
int n=Optional.<Integer>empty().orElse(5);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: n=5

Why this result follows: A fallback applies only under the chosen absence policy.

7. Explicit absence trace 7

Problem: Trace an eager fallback for a present value.

  1. The fallback argument is evaluated before orElse is invoked.
  2. The present value a is returned after the fallback call.
java Illustrative fragment
Optional.of("a").orElse(fallback()); // fallback increments calls, returns "b"

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: result="a"; calls=1

Why this result follows: An unused fallback value can still have an effect.

8. Explicit absence trace 8

Problem: Trace a lazy fallback for a present value.

  1. The Optional already has value a.
  2. orElseGet does not invoke its supplier in this branch.
java Illustrative fragment
Optional.of("a").orElseGet(() -> fallback()); // fallback increments calls

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: result="a"; calls=0

Why this result follows: A supplier defers fallback work until absence.

9. Explicit absence trace 9

Problem: Trace a lazy fallback for absence.

  1. The Optional has no value.
  2. orElseGet invokes its supplier and returns b.
java Illustrative fragment
Optional.<String>empty().orElseGet(() -> fallback()); // fallback returns "b" and increments calls

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: result="b"; calls=1

Why this result follows: The empty branch performs the documented fallback.

10. Explicit absence trace 10

Problem: Map a present String to its length.

  1. The mapper receives cat.
  2. Its length is three UTF-16 code units. map preserves presence for a non-null mapper result.
java Illustrative fragment
Optional.of("cat").map(String::length);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional[3]

Why this result follows: map preserves presence for a non-null mapper result.

11. Explicit absence trace 11

Problem: Map an empty Optional in this stated fragment?

  1. No value is present to pass to the mapper.
  2. The result remains empty.
java Illustrative fragment
Optional.<String>empty().map(String::length);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional.empty

Why this result follows: The mapper is not invoked for absence.

12. Explicit absence trace 12

Problem: Interpret a null map result.

  1. The mapper executes for the present value.
  2. Optional.map treats its null result as empty.
java Illustrative fragment
Optional.of("a").map(s -> (String)null);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional.empty

Why this result follows: The domain must decide whether that absence is legitimate.

13. Explicit absence trace 13

Problem: Transform using an Optional-returning mapper.

  1. The mapper returns Optional containing 3.
  2. flatMap returns that single Optional layer.
java Illustrative fragment
Optional.of("cat").flatMap(s -> Optional.of(s.length()));

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional[3]

Why this result follows: flatMap avoids nesting for an Optional-returning mapper.

14. Explicit absence trace 14

Problem: Identify a nested Optional result.

  1. The mapper itself returns Optional<Integer>.
  2. map wraps that non-null mapper result in another Optional.
java Illustrative fragment
Optional.of("cat").map(s -> Optional.of(s.length()));

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional<Optional<Integer>> containing Optional[3]

Why this result follows: map and flatMap have different result shapes.

15. Explicit absence trace 15

Problem: Filter a present value that fails a predicate.

  1. The contained value is 4.
  2. The predicate 4 > 5 is false.
java Illustrative fragment
Optional.of(4).filter(n -> n>5);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional.empty

Why this result follows: filter represents a failed predicate as absence.

16. Explicit absence trace 16

Problem: Filter a present value that passes a predicate.

  1. The contained value is 6.
  2. The predicate 6 > 5 is true.
java Illustrative fragment
Optional.of(6).filter(n -> n>5);

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: Optional[6]

Why this result follows: A passing present value remains present.

17. Explicit absence trace 17

Problem: Trace the no-argument failure policy for absence.

  1. The Optional has no value to return.
  2. The no-argument orElseThrow throws its specified exception.
java Illustrative fragment
Optional.<String>empty().orElseThrow();

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: NoSuchElementException

Why this result follows: A caller can choose a different explicit exception supplier.

18. Explicit absence trace 18

Problem: Observe a shared mutable contained value.

  1. The Optional holds the list reference, not a deep copy.
  2. The external add changes the same list object.
java Illustrative fragment
Optional<List<Integer>> x=Optional.of(list); // list=[1]; list.add(2)

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: x contains list [1,2]

Why this result follows: Optional does not freeze or isolate the contained object.

19. Explicit absence trace 19

Problem: Count elements from an empty Optional stream.

  1. An empty Optional supplies an empty sequential stream.
  2. The stream count is therefore zero.
java Illustrative fragment
Optional<String> x=Optional.empty(); long n=x.stream().count();

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: n=0

Why this result follows: Optional.stream contains zero or one element.

20. Explicit absence trace 20

Problem: Trace eager fallback failure for a present value.

  1. Java evaluates the fallback argument before the call.
  2. The thrown exception prevents orElse from returning the present value.
java Illustrative fragment
Optional.of("a").orElse(failingFallback()); // fallback throws before returning

This fragment requires surrounding context and imports where needed; it was not executed as a standalone program for this example.

Expected result: fallback exception propagates

Why this result follows: An eager unused fallback can still fail the expression.

Common errors and fixes

get fails on an empty result

Why it happens
Presence was assumed.
How to fix it
Handle absence explicitly.
Prevent it next time
Test the empty path.

A fallback runs unnecessarily

Why it happens
orElse evaluates its argument before the call.
How to fix it
Use orElseGet when lazy evaluation is needed.
Prevent it next time
Test supplier execution.

An error is hidden as absence

Why it happens
Distinct outcomes were collapsed.
How to fix it
Preserve required failure information.
Prevent it next time
Document each outcome.

20 practice exercises

1. What does Optional.of(0).orElse(5) return?

Show hint

Zero is a present value, not absence.

Show worked solution

It returns zero because the Optional contains a value.

Optional.of(0) contains zero, so orElse(5) returns zero rather than the fallback. Compare it with Optional.empty, which selects 5 under this contract.

Check your solution

  • The present value yields 0.
  • The empty case selects 5.

2. Why might a failed network request need more than Optional.empty?

Show hint

Does the caller need to distinguish failure reasons?

Show worked solution

Absence does not identify the cause. Preserve an explicit failure when the caller must distinguish a timeout from invalid data.

Optional.empty does not identify why a value is missing. If the caller must distinguish timeout from invalid data, preserve those failures explicitly and reserve empty for successful absence defined by the contract.

Check your solution

  • Timeout remains distinguishable from invalid data when required.
  • A network failure is not automatically reported as successful absence.

3. A lookup may return present 0, present 3, or no value. Design assertions that distinguish all three without using a numeric sentinel.

Show hint

Presence and contained value are separate observations.

Show worked solution

Assert Optional.of(0) is present with value 0, Optional.of(3) is present with value 3, and Optional.empty is empty. Do not map missing to zero unless the contract explicitly permits that loss.

Check your solution

  • Present zero and present three remain distinct values.
  • The empty case has no contained value.

4. A search can find an order, find none, or time out. Define a return and failure contract that preserves these outcomes.

Show hint

A timeout is not necessarily a successful absence.

Show worked solution

Return a present Optional for a found order and empty for a successful no-match search. Propagate or translate the timeout as an explicit failure with appropriate context; test all three outcomes separately.

Check your solution

  • A successful no-match search returns empty.
  • A timeout is observable separately from absence.

5. A method promises Optional<String> but returns null for no result. Repair the contract and design a caller test.

Show hint

Do not create two absence channels.

Show worked solution

Return Optional.empty for the documented no-result case instead of null. Test that the returned Optional object is non-null and empty, and separately test a present string.

Check your solution

  • The no-result return is a non-null empty Optional.
  • A found value is present.

6. A constructor receives null where absence is allowed, while another requires a value. Compare ofNullable and of.

Show hint

Select the factory from the boundary contract.

Show worked solution

Use ofNullable when null is a documented absence, yielding empty. Use of when null violates the required-value contract, causing a NullPointerException; test a non-null value as a control.

Check your solution

  • The optional-absence path returns empty.
  • The required-value path rejects null.

7. A caller invokes get on a possibly empty order result. Design a safe not-found policy and a present control.

Show hint

Decide what absence means before accessing the value.

Show worked solution

Use an explicit branch or orElseThrow with a documented not-found exception when the caller requires an order. Test empty produces that specified failure and a present order is returned unchanged.

Check your solution

  • Empty follows the documented not-found policy.
  • The present order is returned.

8. A fallback loads a profile and increments a counter. Compare present and empty cases using orElseGet.

Show hint

The supplier is invoked only for absence.

Show worked solution

With a present profile, assert the original is returned and the counter remains 0. With empty, assert the fallback profile is returned and the counter becomes 1; reset the fixture between cases.

Check your solution

  • The present case does not call the supplier.
  • The empty case calls the supplier once.

9. A present Optional uses orElse(expensive()) and expensive throws. Explain the outcome and repair it when fallback should run only if empty.

Show hint

Argument evaluation happens before orElse.

Show worked solution

The eager argument throws before orElse can return the present value. Use orElseGet(() -> expensive()) under the lazy policy; test that a present value returns without calling the supplier and an empty case follows its failure policy.

Check your solution

  • The eager expression can throw despite presence.
  • The lazy present case does not invoke expensive.

10. An Optional<String> contains "12" and must produce an Optional<Integer>; invalid numeric text must remain a failure. Design the mapping and tests.

Show hint

A mapper exception is not the same as an empty input.

Show worked solution

Map with Integer::parseInt for the present value under this contract: "12" becomes Optional[12], empty remains empty, and malformed text throws NumberFormatException. Do not catch that exception and silently return empty unless explicitly specified.

Check your solution

  • Valid text produces present 12 and empty stays empty.
  • Malformed text remains a distinct failure.

11. A mapper returns null for an invalid record, but invalid must be reported as an error. Why is Optional.map alone insufficient?

Show hint

map turns a null mapper result into empty.

Show worked solution

A null mapper result becomes Optional.empty, collapsing invalid data into absence. Make the mapper reject invalid data explicitly or return a richer documented result, and test invalid, absent, and valid records independently.

Check your solution

  • Invalid data produces the specified failure rather than accidental empty.
  • A genuine absent record remains distinguishable.

12. A function findAddress(User) returns Optional<Address>. Compare user.map(this::findAddress) with flatMap and state the output types.

Show hint

The mapper already returns Optional.

Show worked solution

map produces Optional<Optional<Address>>, while flatMap produces Optional<Address> if the mapper returns a non-null Optional. Test a present user with an address, a present user without one, and an empty user.

Check your solution

  • map has two Optional layers.
  • flatMap has one layer and preserves absence.

13. A filter requires a positive quantity. Compare Optional.of(0), Optional.of(2), and empty after filtering.

Show hint

filter can turn a present value into empty.

Show worked solution

The zero value fails the predicate and becomes empty, 2 remains present, and the initially empty Optional remains empty without invoking the predicate. Ensure the contract permits merging rejected zero with absence before using this design.

Check your solution

  • Zero and initial absence both yield empty.
  • Two remains present.

14. An Optional<List<MutableItem>> must expose an independent result. Design container and element ownership tests.

Show hint

Optional itself does not copy contained state.

Show worked solution

Copy the list structure and either copy each mutable item or use immutable item values under the contract. Mutate the original list and an original item after the call; assert the returned value remains unchanged, then test the empty result separately.

Check your solution

  • Source structural mutation does not alter the result.
  • Source element mutation does not alter the promised independent result.

15. Two threads synchronize on Optional.empty() expecting the same monitor. Explain why this is an invalid design and provide an alternative.

Show hint

Optional is value-based and its identity is not a synchronization contract.

Show worked solution

Do not use Optional instances as locks or assume empty is a singleton. Use a dedicated final lock owned by the shared state, or an appropriate concurrency primitive, and test the actual protected invariant.

Check your solution

  • The lock is independent of Optional identity.
  • The shared invariant is protected by the chosen synchronization.

16. A list contains Optional.of("a"), empty, and Optional.of("b"). Use Optional.stream to derive the present sequence.

Show hint

Each Optional contributes zero or one element.

Show worked solution

Flatten each Optional’s stream in encounter order to obtain [a,b]; the empty Optional contributes no element. Assert the two values and their order without treating absence as an empty string.

Check your solution

  • The flattened sequence is [a,b].
  • The empty Optional contributes no element.

17. A fallback default of 10 is acceptable for missing page size, but explicit zero must be rejected. Design the branches and tests.

Show hint

Do not equate present zero with absence.

Show worked solution

Use the default only for Optional.empty. For a present value validate the 1–100 range: zero is rejected and 20 accepted. Test all three cases so fallback does not mask invalid input.

Check your solution

  • Empty selects 10.
  • Present zero is rejected while 20 is accepted.

18. A fallback supplier is called twice because two separate empty lookups are evaluated. If only one call is allowed per request, design an ownership and test policy.

Show hint

Laziness does not imply caching.

Show worked solution

Evaluate or memoize the fallback once in the request-owned scope under the documented policy, then reuse that result. Use a counter to assert one call across the two consumers, and separately test the present path makes no fallback call.

Check your solution

  • The empty request invokes the fallback once.
  • The present path does not invoke it.

19. A method returns empty for both not-found and unauthorized. When is Optional alone insufficient, and what should tests assert?

Show hint

One empty value cannot carry two actionable reasons.

Show worked solution

If callers must react differently, define distinct documented outcomes, such as an authorization failure and an empty successful search. Test both independently and ensure public responses respect the chosen disclosure policy.

Check your solution

  • Not-found and unauthorized are distinguishable where required.
  • Public behavior follows the explicit disclosure policy.

20. A test asserts only that an Optional is present. The expected count is zero and a buggy implementation returns 5. Strengthen the test.

Show hint

Presence is not value correctness.

Show worked solution

Assert presence and the contained value 0, then add empty and present-nonzero controls. The buggy value 5 passes a presence-only check but fails the value assertion.

Check your solution

  • The test rejects present 5 when zero is expected.
  • Empty and present-nonzero cases are separately covered.

Key takeaways

  • Optional represents expected absence.
  • Keep failure and fallback policies explicit.
  • Present zero is not an empty Optional.
  • orElse evaluates its argument eagerly while orElseGet defers the supplier to absence.
  • Optional does not make its contained object immutable or thread-safe.

Official references