orElseGet accepts a Supplier so the fallback value is computed lazily, only when the Optional is empty, unlike orElse whose argument is always evaluated even when the Optional already holds a value.
int[] fallbackCalls = {0};
Supplier<String> fallback = () -> {
fallbackCalls[0]++;
return "default";
};
Optional<String> present = Optional.of("configured");
Optional<String> empty = Optional.empty();
System.out.println("present: " + present.orElseGet(fallback));
System.out.println("empty: " + empty.orElseGet(fallback));
System.out.println("fallback calls: " + fallbackCalls[0]);
present: configured
empty: default
fallback calls: 1
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27