Course contentsShow
← Java
Lesson 1811 of 2,87037. Optional for Null SafetyFree lesson

or vs orElse: Returning Optional vs Unwrapping

Understand the key difference: or() returns Optional<T> while orElse/orElseGet return T directly.

or vs orElse: Returning Optional vs Unwrapping

What you'll learn: You'll understand the fundamental difference between or() and the orElse family—one keeps you in the Optional world, the other pulls you out.

The Core Distinction

The or() method and the orElse family (orElse, orElseGet, orElseThrow) serve similar purposes—providing alternatives when an Optional is empty—but they differ dramatically in what they return.

or() returns Optional<T>: It gives you another Optional to continue chaining operations functionally. You stay within the Optional container.

orElse/orElseGet/orElseThrow return T: They unwrap the value (or provide a substitute), giving you the actual object. You exit the Optional world.

When to Use Which

Use or() when you want to try alternative sources but keep working with Optional:

Optional<String> primary = findInCache(id);
Optional<String> result = primary.or(() -> findInDatabase(id));
// result is still Optional<String>, can continue chaining

Use orElse/orElseGet when you're ready to extract a value and need the actual object:

String value = findInCache(id)
    .orElseGet(() -> loadDefault());
// value is String, not Optional<String>

The Analogy

Think of Optional as a gift box. The or() method says, "If this box is empty, try this other box instead"—you're still dealing with boxes. The orElse methods say, "Open the box and give me what's inside, or use this default"—you're taking the contents out.

Key Takeaway: Use or() when you need to chain alternative Optional sources; use orElse/orElseGet/orElseThrow when you're ready to unwrap and extract the final value.