Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.empty()

Returns an empty `Optional` — no value.

Available since: Java 8

Syntax

static <T> Optional<T> empty()

Return value

Optional<T>An empty `Optional`.

Examples

Returning nothing found:

Optional<Integer> parsePositive(String s) {
    int n = Integer.parseInt(s);
    return n > 0 ? Optional.of(n) : Optional.empty();
}
 
void main() {
    IO.println(parsePositive("42"));
    IO.println(parsePositive("-5"));
}

Output:

Optional[42]
Optional.empty

Notes

Return Optional.empty() instead of null from methods whose type is Optional. An empty Optional prints as Optional.empty.

See also

  • Optional.of() — Creates an `Optional` holding a non-null value.
  • Optional.isPresent() — Checks whether an `Optional` holds a 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.