Last Updated : 12 Jul, 2025
The isPresent() method of the java.util.Optional class is used to check if a value is present in the Optional object. If there is no value present in this Optional instance, then this method returns false, else true.
Syntax of Optional isPresent() Methodpublic boolean isPresent()
Now let us see some examples of the Optional isPresent() method.
Example 1: Using Optional.of()
This example finds out that a value is present inside a non-empty Optional.
Java
// Java program to demonstrate Optional.isPresent()
// with a non-empty Optional
import java.util.Optional;
public class Geeks {
public static void main(String[] args) {
// Create an Optional with a non-null value
Optional<Integer> optional = Optional.of(9455);
// Print the Optional value
System.out.println("Optional: " + optional);
// Check if a value is present
System.out.println("Is any value present: " + optional.isPresent());
}
}
Optional: Optional[9455] Is any value present: true
Example 2: Using Optional.empty()
This example shows how isPresent() returns false for an empty Optional.
Java
// Java program to demonstrate Optional.isPresent()
// with an empty Optional
import java.util.Optional;
public class Geeks {
public static void main(String[] args) {
// Create an empty Optional
Optional<Integer> optional = Optional.empty();
// Print the Optional value
System.out.println("Optional: " + optional);
// Check if a value is present
System.out.println("Is any value present: "
+ optional.isPresent());
}
}
Optional: Optional.empty Is any value present: false
Note: The isPresent() method is still valid, but it is not the preferred approach for Java 11+ development. Consider using alternatives like ifPresent(), orElse().
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4