Java 25 (LTS) reference · Optional
Java Optional orElse() Method
Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed.
Java 25 (LTS) Since Java 8
Syntax
optional.orElse(other)
Parameters
| Parameter | Description |
|---|---|
otherT |
The default value. |
Return value
The value or the default.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println(Optional.of("dark").orElse("light"));
System.out.println(Optional.<String>empty().orElse("light"));
}
}
Output
dark light
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] calls = {0};
Optional<String> present = Optional.of("cached");
present.orElse(expensive(calls)); // runs expensive() even though a value is present
present.orElseGet(() -> expensive(calls)); // doesn't run it
System.out.println("expensive() ran " + calls[0] + " time(s)");
}
static String expensive(int[] calls) {
calls[0]++;
return "computed";
}
}
Output
expensive() ran 1 time(s)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
optional.orElseThrow()· Return the value if present, otherwise throw: NoSuchElementException by default, or an exception you supply.optional.map()· Transform the value inside an Optional if present; an empty Optional stays empty. Chains safely without null checks.- Java Optional · tutorial