Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Optional.isPresent()

Checks whether an `Optional` holds a value.

Available since: Java 8

Syntax

boolean isPresent()
boolean isEmpty()

Return value

boolean`isPresent()` returns `true` if a value is present; `isEmpty()` (Java 11) is the opposite.

Examples

Checking and reading:

void main() {
    Optional<String> found = Stream.of("pen", "book").filter(s -> s.startsWith("b")).findFirst();
    if (found.isPresent()) {
        IO.println("Found " + found.get());
    }
    IO.println(Optional.empty().isEmpty());
}

Output:

Found book
true

Notes

The isPresent() + get() pair works, but ifPresent(), orElse() or map() are usually shorter and safer. Calling get() on an empty Optional throws NoSuchElementException.

See also

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.