Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.of()

Creates an `Optional` holding a non-null value.

Available since: Java 8

Syntax

static <T> Optional<T> of(T value)

Parameters

ParameterTypeDescription
valueTA 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
NullPointerException

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.