CKTIS / Java
Optional.isPresent() — test whether a value is present
Check whether an `Optional` contains a value without retrieving it. Use `isPresent()` when you need a `boolean` and `ifPresent(...)` when you only want to act on the value if it exists.
Version: Java SE 21
Syntax
public boolean isPresent()
// Call on an Optional<T> instance:
boolean hasValue = optional.isPresent();Optional.isPresent is shorthand for the method Optional.isPresent(). It is a no-argument instance method of java.util.Optional<T>: call it as optional.isPresent(), not as a static call on the class.
It returns a boolean: true if the Optional holds a non-null value and false if it is empty. It neither retrieves the value nor changes the Optional. Even the empty string "" counts as a value. If the optional reference itself is null, the call throws NullPointerException rather than returning false.
Use isPresent() when you need a condition, such as in an if statement. To test for absence instead, optional.isEmpty() is equivalent to !optional.isPresent().
If all you want to do is print the value when present, use optional.ifPresent(System.out::println) instead of a separate if and get() call. ifPresent(...) passes the value to the action and does nothing for an empty Optional. Calling get() on an empty Optional throws NoSuchElementException.
Examples
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> found = Optional.of("Ada");
Optional<String> missing = Optional.empty();
System.out.println(found.isPresent());
System.out.println(missing.isPresent());
found.ifPresent(System.out::println);
missing.ifPresent(System.out::println);
}
}Result
true false Ada
The first two lines are the results of `isPresent()`: `true` and `false`. Only `found` holds a value, so the two `ifPresent(...)` calls add just one line: `Ada`.
Related lessons
- Java · Lesson 66 · Basic · Version: 2
- Java · Lesson 47 · Intermediate · Version: 2