Optional makes a potentially missing return value explicit. It should guide control flow rather than merely wrap nullable data.
Before you start
You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.
The practical goal is to reason through this situation: A repository lookup returns Optional.empty when no record exists. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Model normal absence
A missing lookup can be a documented result rather than an exception.
Step 2: Branch or provide a fallback
Avoid get unless presence has already been established.
Step 3: Defer expensive fallback
Use orElseGet when fallback computation should run only for absence.
Worked scenario
A repository lookup returns Optional.empty when no record exists.
String name = java.util.Optional.of("Ada")
.orElseGet(() -> "Guest");With orElse(expensiveCall()), the argument is evaluated before the method runs even if a value exists. The supplier form defers evaluation; it does not make an unavailable dependency automatically recoverable.
Common mistake
Calling get without checking moves the failure rather than handling absence.
Verify the behavior
Count fallback executions for present and empty values and test null-policy boundaries.
Interview exercise
Choose a fallback efficiently.
Answer and reasoning
Use orElseGet when computing the fallback is expensive, since orElse evaluates its argument before the call.
Continue learning
Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.