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.


Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!