Java Optional isPresent() Method
Example
Check if two Optional objects have a value:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
Optional<String> noName = Optional.empty();
System.out.println(name.isPresent());
System.out.println(noName.isPresent());
}
}
Definition and Usage
The isPresent() method checks if the Optional has a value.
Use it before you call get(), because get() throws an exception when the Optional is empty.
Syntax
public boolean isPresent()
Parameter Values
None.
Technical Details
| Returns: | true if there is a value, otherwise false. |
|---|
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods