Open In App

Optional isPresent() Method in Java

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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() Method

public boolean isPresent()

  • Parameters: This method does not accept any parameters.
  • Return value: This method returns a Boolean value stating whether there is a value present in this Optional instance.

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());
    }
}

Output
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());
    }
}

Output
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().



Practice Tags :

Similar Reads