Java Optional of() Method
Example
Create an Optional with a value:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
System.out.println(name.isPresent());
System.out.println(name.orElse("Guest"));
}
}
Definition and Usage
The of() method returns an Optional that holds the value you give it.
The value must not be null. If it is null, the method throws a NullPointerException.
Tip: If the value can be null, use ofNullable() instead.
Syntax
public static <T> Optional<T> of(T value)
T refers to the data type of the value.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value to put in the Optional. It must not be null. |
Technical Details
| Returns: | An Optional that holds the value. |
|---|---|
| Throws: | NullPointerException - if the value is null. |
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods