Optional empty, of, ofNullable() Methods

In this tutorial, we will demonstrate the different ways to create Optional class objects in Java.

The Optional class was introduced in Java 8 to avoid null checks and NullPointerException.

The Optional class provides empty(), of(), ofNullable() methods to create it's objects.

Create Optional Class Object in Java - empty(), of(), ofNullable() Methods

There are several ways of creating Optional objects.

empty() Method

To create an empty Optional object, we simply need to use its empty() static method:
        Optional<Object> emptyOptional = Optional.empty();

of() Method

The of() static method returns an Optional with the specified present non-null value.

        Optional<String> emailOptional = Optional.of("ramesh@gmail.com");

ofNullable() Method

The ofNullable() static method returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
        Optional<String> stringOptional = Optional.ofNullable("ramesh@gmail.com");

Here is the complete example with output:

import java.util.Optional;

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

        String email = "ramesh@gmail.com";

        // of, empty, ofNullable
        Optional<Object> emptyOptional = Optional.empty();
        System.out.println(emptyOptional);

        Optional<String> emailOptional = Optional.of(email);
        System.out.println(emailOptional);

        Optional<String> stringOptional = Optional.ofNullable(email);
        System.out.println(stringOptional);
    }
}

Output:

Optional.empty
Optional[ramesh@gmail.com]
Optional[ramesh@gmail.com]

Comments