CKTIS / Java
Optional.orElse: practical reference
Optional.orElse: practical reference: Optional.orElse(other) returns the present value, or the supplied other object when the Optional is empty.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Optional.orElse(...)Optional.orElse(other) returns the present value, or the supplied other object when the Optional is empty.
Use it for a cheap, already available default whose construction performs no work or side effects worth avoiding.
The other argument is evaluated before the call, so an expensive method runs even when the Optional contains a value.
other may be null and is returned for an empty Optional; a present Optional value always takes precedence.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var value = java.util.Optional.of("present").orElse("fallback");
System.out.println(value);
}
}
Result
present
The example exercises the documented element in a small deterministic program and compares exact standard output.