Java Optional orElse() Method
Example
Get the name, or "Guest" if there is no name:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
Optional<String> noName = Optional.empty();
System.out.println(name.orElse("Guest"));
System.out.println(noName.orElse("Guest"));
}
}
Definition and Usage
The orElse() method returns the value in the Optional. If the Optional is empty, it returns the default value that you give it.
This is the safest way to get the value, because it never throws an exception.
Tip: If the default value takes work to create, use orElseGet(). It only creates the default value when it is needed.
Syntax
public T orElse(T other)
T refers to the data type of the value in the Optional.
Parameter Values
| Parameter | Description |
|---|---|
| other | Required. The default value to return if the Optional is empty. |
Technical Details
| Returns: | The value if there is one, otherwise other. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods