How to create an empty Optional Instance in Java


The Optional class from java.util package is a container object that may or may not contain a non-null value, it is primarily used as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors.

We can create an empty Optional instance with the help of the empty() method.


    Syntax:
    public static <T> Optional<T> empty()

    This method will return an empty Optional instance with no value.


    Example:

        public static void main(String[] args) {
    
            Optional<String> emptyOptional = Optional.empty();
    
            if (!emptyOptional.isPresent()) {
                System.out.println("The Optional is empty.");
            } else {
                System.out.println("The Optional is not empty.");
            }
        }
    Output:

    The Optional is empty.


Note: Make use of either of isEmpty() or isPresent() to check if the object returned by Optional.empty() is empty or not.


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap