Optional isPresent Method

In this tutorial, we will demonstrate how to check a value is present in an Optional class object using the isPresent() method.

Optional isPresent() Method Example

The isPresent() method returns true if there is a value present, otherwise false.

In the below example, the isPresent() method returns true and prints the value:

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        if(stringOptional.isPresent()){
            System.out.println(stringOptional.get());
        }else{
            System.out.println("no value present");
        }
    }
}
Output:
ramesh@gmail.com

In the below example, the isPresent() method returns false and prints the message as "no value present":

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        if(stringOptional.isPresent()){
            System.out.println(stringOptional.get());
        }else{
            System.out.println("no value present");
        }
    }
}
Output:
no value present
Note that we used the isPresent() method to check if there is a value inside the Optional object.

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments