Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.orElse()

Returns the value, or a fallback if there is none.

Available since: Java 8

Syntax

T orElse(T other)

Parameters

ParameterTypeDescription
otherTThe default value.

Return value

TThe value from the `Optional`, or `other`.

Examples

A user name or guest:

void main() {
    Optional<String> name = Optional.empty();
    IO.println(name.orElse("guest"));
    IO.println(Optional.of("Anna").orElse("guest"));
}

Output:

guest
Anna

Notes

The argument is always evaluated, even when a value is present. If the fallback is expensive to create (a query, a big object), use orElseGet().

See also

Related recipes

In the tutorial

  • Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.

Thanks for reading!

Donate to the site — we work hard for you.