CodeBlanks Logo Icon CodeBlanks

orElse and orElseGet

Learn default values with orElse and orElseGet.

Default value: orElse

orElse(default) returns the value if present, otherwise the given default. This is the simplest way to handle an empty Optional safely.

Example: opt.orElse("Guest"). If opt is empty the result is "Guest"; if not, the inner value is returned. One caveat: the expression passed to orElse is always evaluated, even when opt is present. If it is an expensive computation this is wasteful; for such cases orElseGet is a better fit.

Lazy default: orElseGet

orElseGet(Supplier) also returns a default value; but it produces the default lazily through a Supplier. The default is computed only when the Optional is empty.

Example: opt.orElseGet(() -> fetchFromDb()). If opt is present fetchFromDb is never called; if empty, it is called. This saves performance on expensive operations compared to orElse. Because a Supplier is a function re-evaluated on each call, it is also safer in code with side effects.

Practice Give a default to an empty Optional

Create an empty Optional<String> with Optional.empty(). Use orElse("Guest") to get the default value. Print the result with System.out.println.

Starter code

Main.java
import java.util.Optional;

// Create an empty Optional
// Use orElse with "Guest" as default
// Print the result

Sample solution

Main.java
import java.util.Optional;

public class OrElseDefault {
    public static void main(String[] args) {
        Optional<String> name = Optional.empty();
        String result = name.orElse("Guest");
        System.out.println(result);
    }
}

Expected output

Guest

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the orElse call

Question
String result = opt.____("Misafir");
Answer
String result = opt.orElse("Misafir");

Explanation: orElse returns the default when the value is absent.

2 Match the orElse family

Term Meaning
orElse Value or default
orElseGet Takes a Supplier
orElseThrow Throws an error
orElse(default) Always evaluated

3 Which method takes a Supplier for the default value?

  • orElse
  • orElseGet Correct answer
  • ifPresent
  • orElseThrow

Explanation: orElseGet takes a Supplier and produces the default lazily.

All lessons in Advanced