Sobes.tech
Junior — Middle

How can it be determined whether an Optional object contains a value?

sobes.tech AI

Answer from AI

To determine whether an Optional object contains a value, the isPresent() method is used. It returns true if there is a value inside the Optional, and false if the object is empty.

Example:

Optional<String> optional = Optional.of("Hello");
if (optional.isPresent()) {
    System.out.println("Value: " + optional.get());
} else {
    System.out.println("Value is absent");
}

Also, from Java 11 onwards, you can use the isEmpty() method, which returns true if there is no value.