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

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

The Optional class 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("");

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("");

Here is the complete example with output:

import java.util.Optional;

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

        String email = "";

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

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

        Optional<String> stringOptional = Optional.ofNullable(email);



Related Optional Class Method Examples