What is the Optional. ofNullable() method in Java?

In Java, the Optional object is a container object which may or may not contain a value. The Optional class is present in the java.util package.

Note: You can read more about the Optional class here.

What is the ofNullable() method of the Optional class?

The ofNullable() method is used to get an instance of the Optional class with a specified value.

If the value is null, then an empty Optional object is returned.

public static <T> Optional<T> ofNullable(T value)

Argument

This method takes a value that will be present in the Optional object.

Return value

This method returns an Optional object with the specified value. If the argument value is null, then an empty Optional object is returned.

Code

The below code shows how to use the ofNullable() method:

import java.util.Optional;
class OptionalOfNullableExample {
public static void main(String[] args) {
Optional<Integer> optional1 = Optional.ofNullable(1);
System.out.println("Optional1: " + optional1);
Optional<String> optional2 = Optional.ofNullable(null);
System.out.println("\n\nOptional2: " + optional2);
System.out.println("Optional2.isPresent: " + optional2.isPresent());
}
}

Explanation

In the above code:

  • In line 1, we import the Optional class.
import java.util.Optional;
  • In line 5, we use the ofNullable() method to get an Optional object of the Integer type with value 1.
Optional<Integer> optional1 = Optional.ofNullable(1);
optional1;// Optional[1]
  • In line 8, we call the ofNullable() method with null as an argument. This method returns an empty Optional object because we send null as the value for the Optional object.
Optional<String> optional2 = Optional.ofNullable(null);
optional2;// Optional.empty
optional2.isPresent(); // false

Free Resources