Sub topic 7
orElse vs orElseGet: When Defaults Are Computed
You already know two ways to get a value out of an Optional with a fallback: orElse and orElseGet. They look almost the same, and most of the time they return the same result. They differ in when the default value is made. This chapter shows that difference, explains why it can matter, and gives you a simple rule for choosing between them.
Two Methods, One Result
Here is a quick reminder of how each method is written:
String a = city.orElse("Unknown");
String b = city.orElseGet(() -> "Unknown");Both lines give you the city if one is present. Both give you "Unknown" if the Optional is empty. So why have two methods?
The answer is in what you pass to each one:
orElsetakes a value. That is the default itself, already made.orElseGettakes a Supplier. A Supplier is a small piece of code, usually a lambda like() -> "Unknown", that can make a value when asked.Supplieris an interface injava.util.functionwith one method,get(), which takes no input and returns a value.
Handing over a value and handing over a recipe for a value lead to different behavior.
Eager and Lazy Evaluation
Two terms describe this behavior:
- Eager evaluation means the work happens right away, whether or not the result is needed.
- Lazy evaluation means the work waits until the result is actually needed. If it is never needed, the work never happens.
orElse is eager. Java must work out the argument before it can call any method, so orElse(makeDefault()) runs makeDefault() first. Then orElse checks whether the Optional has a value. If it does, the default you just built is thrown away.
orElseGet is lazy. Java builds the lambda, but the code inside the lambda does not run yet. orElseGet first checks the Optional. It calls the Supplier only if the Optional is empty.
Seeing the Difference
The program below makes the difference visible. The method makeDefault() prints a line every time it runs. Watch when that line appears.
import java.util.Optional;
public class EagerLazyDemo {
static String makeDefault() {
System.out.println(" makeDefault() was called");
return "Guest";
}
public static void main(String[] args) {
Optional<String> present = Optional.of("Ada");
Optional<String> empty = Optional.empty();
System.out.println("orElse, value present:");
String a = present.orElse(makeDefault());
System.out.println(" result: " + a);
System.out.println("orElseGet, value present:");
String b = present.orElseGet(() -> makeDefault());
System.out.println(" result: " + b);
System.out.println("orElse, empty:");
String c = empty.orElse(makeDefault());
System.out.println(" result: " + c);
System.out.println("orElseGet, empty:");
String d = empty.orElseGet(() -> makeDefault());
System.out.println(" result: " + d);
}
}Running it prints:
orElse, value present:
makeDefault() was called
result: Ada
orElseGet, value present:
result: Ada
orElse, empty:
makeDefault() was called
result: Guest
orElseGet, empty:
makeDefault() was called
result: GuestLook at the first two cases. The result is Ada both times. But with orElse, makeDefault() still ran, and its work was wasted. With orElseGet, it never ran.
When the Optional is empty, both methods run makeDefault() exactly once. The difference only shows up when a value is present.
When the Difference Matters
If the default is a fixed value such as "Unknown", 0, or an existing constant, there is nothing to waste. Making a string literal costs nothing. In that case orElse is fine, and it is easier to read.
The difference matters in two situations: when the default is expensive to build, and when building it has a side effect.
Expensive defaults
Some defaults take real work. They may read a file, call a web service, query a database, or run a long calculation. With orElse, that work happens on every call, even when you already have a value. If the code runs thousands of times, the wasted time adds up.
// Slow: loadDefaultSettings() runs every time, even when settings exist
Settings s = savedSettings.orElse(loadDefaultSettings());
// Better: loadDefaultSettings() runs only when nothing was saved
Settings s = savedSettings.orElseGet(() -> loadDefaultSettings());Settings, savedSettings, and loadDefaultSettings are placeholder names in this snippet. The pattern is what counts.
Defaults with side effects
A side effect is a change a method makes outside itself, such as saving a record, writing to a log, sending an email, or adding to a list. If the default has a side effect, orElse causes that effect even when you never use the default. This is a real bug, not just a slowdown.
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class SideEffectDemo {
static final List<String> savedUsers = new ArrayList<>();
static String createGuestUser() {
String guest = "guest-" + (savedUsers.size() + 1);
savedUsers.add(guest); // side effect: saves a new user
return guest;
}
public static void main(String[] args) {
Optional<String> loggedIn = Optional.of("grace");
String user1 = loggedIn.orElse(createGuestUser());
System.out.println(user1); // grace
System.out.println(savedUsers); // [guest-1] <- a guest was saved anyway
String user2 = loggedIn.orElseGet(SideEffectDemo::createGuestUser);
System.out.println(user2); // grace
System.out.println(savedUsers); // [guest-1] <- no new guest this time
}
}The user grace was logged in the whole time, yet the orElse line still saved a guest account nobody asked for. In a real system that could mean junk rows in a database or emails sent by mistake. The orElseGet line saved nothing extra.
Notice the method reference SideEffectDemo::createGuestUser. It works as a Supplier because createGuestUser takes no arguments and returns a String. It means the same as () -> createGuestUser().
Edge Cases Worth Knowing
Passing null as the default
orElse(null) is allowed. It returns the value if present, and null if not. People sometimes use it at the edge of older code that still expects null.
A Supplier may also return null. orElseGet(() -> null) acts just like orElse(null).
The Supplier itself must not be null, though. If you write orElseGet(null) and the Optional is empty, Java throws a NullPointerException when it tries to call the missing Supplier.
Mixing up the argument types
Each method expects a specific type. For an Optional<String>:
| Call | Compiles? | Why |
|---|---|---|
| `opt.orElse("Guest")` | Yes | The argument is a `String` |
| `opt.orElseGet(() -> "Guest")` | Yes | The argument is a `Supplier<String>` |
| `opt.orElse(() -> "Guest")` | No | A lambda is not a `String` |
| `opt.orElseGet("Guest")` | No | A `String` is not a Supplier |
When you see a compile error with one of these methods, check this table first.
orElseThrow is lazy too
orElseThrow(() -> new IllegalStateException("No city")) also takes a Supplier. The exception object is built only when the Optional is empty. That is why you pass a lambda there and not a ready-made exception.
Is orElseGet always better?
No. A lambda is a little harder to read than a plain value. For a constant, orElse("Unknown") says exactly what it means, and the lazy version gains you nothing. The trade-off is simple: use orElse for clarity when the default costs nothing, and use orElseGet for safety when it does.
A Simple Rule for Choosing
Ask one question: "Is building the default free and harmless?"
| Kind of default | Example | Use |
|---|---|---|
| Literal or constant | `"Unknown"`, `0`, `DEFAULT_NAME` | `orElse` |
| Variable you already have | `fallbackName` | `orElse` |
| New object built by a method call | `createEmptyCart()` | `orElseGet` |
| Slow work (file, network, database) | `loadFromServer()` | `orElseGet` |
| Anything with a side effect | `saveGuest()`, `sendAlert()` | `orElseGet` |
| You want an exception instead | `new NotFoundException()` | `orElseThrow` with a Supplier |
If you are unsure, orElseGet is the safe choice. It never does extra work.
Exercises
Exercise
An Optional<String> called nickname holds the value "Sam". The code runs nickname.orElse(lookupNickname()), where lookupNickname() prints "looking up". What is the result, and is "looking up" printed?
Show answer
The result is "Sam". Yes, "looking up" is printed, because orElse is eager. Java runs lookupNickname() to get the argument before orElse checks whether a value is present.
Exercise
Rewrite Order order = findOrder(id).orElse(createAndSaveNewOrder()); so that a new order is saved only when no existing order is found.
Show answer
Order order = findOrder(id).orElseGet(() -> createAndSaveNewOrder()); The method reference form works too, for example orElseGet(this::createAndSaveNewOrder) inside an instance method. The Supplier runs only if findOrder returns an empty Optional.
Exercise
Which is the better choice for an Optional<Integer> called score: score.orElse(0) or score.orElseGet(() -> 0)? Explain why.
Show answer
score.orElse(0) is better. The default is a constant that costs nothing to make and has no side effect, so laziness gains nothing, and the plain value is easier to read.
Exercise
An Optional<String> is empty. What happens with opt.orElseGet(() -> null), and what happens with opt.orElseGet(null)?
Show answer
orElseGet(() -> null) returns null, because the Supplier runs and returns null. orElseGet(null) throws a NullPointerException, because the Optional is empty and Java tries to call a Supplier that does not exist.