Optional.of()
Creates an `Optional` holding a non-null value.
Available since: Java 8
Syntax
static <T> Optional<T> of(T value)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | T | A value that is definitely not `null`. |
Return value
Optional<T>An `Optional` holding the value.
Examples
A normal value and null:
void main() {
Optional<String> name = Optional.of("Anna");
IO.println(name.get());
try {
Optional.of(null);
} catch (NullPointerException e) {
IO.println("NullPointerException");
}
}Output:
Anna
NullPointerExceptionNotes
If the value may be null, use Optional.ofNullable() — of(null) immediately throws NullPointerException.
See also
- Optional.ofNullable() — Wraps a value that may be `null` into an `Optional`.
- Optional.empty() — Returns an empty `Optional` — no value.
- Optional — A container that either holds a value or is empty — a replacement for returning `null`.
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.