What is the difference between orElse and orElseGet in Java Optional?
orElse takes a ready value that is always evaluated, even when the Optional has a value. orElseGet takes a Supplier that runs only when the Optional is empty, so use it when the fallback is expensive or has side effects.
Explain it simply
orElse is buying a spare umbrella every morning just in case, whether or not it rains. orElseGet is going to buy one only when you step out and see rain.
Example
import java.util.Optional;
static String fallback() {
System.out.println("computing fallback");
return "default";
}
Optional<String> present = Optional.of("Ravi");
System.out.println(present.orElse(fallback())); // fallback() runs anyway
// prints: computing fallback
// prints: Ravi
System.out.println(present.orElseGet(() -> fallback())); // supplier not called
// prints: RaviWhat to say in the interview
"With orElse(x), the argument x is evaluated before the call, so a database lookup or object creation inside it happens every time. orElseGet(supplier) delays the work until needed. If the fallback is a constant, orElse is fine and slightly simpler. Also useful: orElseThrow for a required value, and map or ifPresent to avoid get(). Optional is for return types, not for fields or method parameters."
Common mistakes
- Calling
optional.get()without checking, which throws NoSuchElementException. - Using Optional for class fields.