Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is the difference between orElse and orElseGet in Java Optional?

SHORT ANSWER

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

java
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: Ravi

What 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.

#java#java8#optional

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.