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

orElse: Providing a Default Value

Learn how orElse returns the contained value or a default if empty, and when to use it for simple fallback scenarios.

orElse: Providing a Default Value

You'll learn how to use orElse() to safely extract a value from an Optional with a fallback.

Now that we know get() is dangerous and isPresent() is verbose, let's look at the right way to work with Optional: providing a default value when the container is empty.

The Core Idea

The orElse(T other) method returns the value inside the Optional if present, or the default value you specify if empty. It's like saying "give me what's in the box, or if the box is empty, give me this backup value instead."

Think of it like a vending machine with a backup dispenser: if your first-choice snack is out of stock, the machine automatically gives you the backup snack you specified. No exceptions, no checking—just a guaranteed result.

The Syntax

Optional<String> name = Optional.ofNullable(getUserName());
String displayName = name.orElse("Guest");

If name contains a value, displayName gets that value. If name is empty, displayName gets "Guest". You always get a non-null result.

When to Use orElse

Use orElse() when:

  • You have a simple, pre-computed default value
  • The default is cheap to create (a constant, literal, or existing variable)
  • You want clean, readable code without conditionals
Optional<Integer> score = getPlayerScore();
int finalScore = score.orElse(0);

Optional<String> config = loadConfig();
String value = config.orElse("default-setting");

Notice: no if statements, no exception handling, just straightforward value extraction with safety built in.

Key Takeaway: orElse() eliminates the need for isPresent()/get() patterns by providing a clean, functional way to extract values with a simple fallback, making your code safer and more readable.