How to create an Empty Optional

Java 8 introduced the java.util.Optional<T> class to reflect an optional value. The following example demonstrates how to create an Empty Optional Java 8 onwards.

​The Name class has a middle name property that is optional. Using Optional.empty ensures application will not run into a NullPointerException (NPE).

import java.util.Optional;

public class Name {
        
    /** Create an empty optional middle name **/
    private Optional<String> middleName = Optional.empty();
        
    public Optional<String> getMiddleName() {
        return middleName;
    }
        
    public void setMiddleName(Optional<String> middleName) {
        this.middleName = middleName;
    }
}

public static void main(String[] args) {
    Name name = new Name();
    System.out.println(name.getMiddleName().toString());
}
                                    

The above block will print Optional.empty rather than causing a NPE.