What is Optional.empty method in Java?

In Java, the Optional object is a container object that may or may not contain a value. We can replace the multiple null checks using the Optional object’s isPresent method.

The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn’t have any value.

The Optional class is present in the java.util package. Read more about Optional class here.

Syntax

public static <T> Optional<T> empty()

Parameter

This method doesn’t take any argument.

Return value

This method returns an Optional object with an empty value.

Code

The code below denotes how to use the empty method.

import java.util.Optional;
class OptionalEmptyExample {
public static void main(String[] args) {
Optional<Integer> optional = Optional.empty();
// print value
System.out.println("Optional: " + optional);
System.out.println("Has value: " + optional.isPresent());
}
}

Explanation

In the code above:

  • In line 1, we imported the Optional class.
import java.util.Optional;
  • In line 5, we used the empty method to get an empty Optional object of the Integer type. The returned object doesn’t have any value.
Optional<Integer> optional = Optional.empty();
  • In line 7, we printed the created Optional object.
System.out.println("Optional: " + optional); // Optional.empty
  • In line 8, we used the isPresent method to check if the object contains a value. We will get false as a result.
optional.isPresent(); // false