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
Optionalclass is present in thejava.utilpackage. Read more aboutOptionalclass 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 valueSystem.out.println("Optional: " + optional);System.out.println("Has value: " + optional.isPresent());}}
Explanation
In the code above:
- In line 1, we imported the
Optionalclass.
import java.util.Optional;
- In line 5, we used the
emptymethod to get an emptyOptionalobject of theIntegertype. The returned object doesn’t have any value.
Optional<Integer> optional = Optional.empty();
- In line 7, we printed the created
Optionalobject.
System.out.println("Optional: " + optional); // Optional.empty
- In line 8, we used the
isPresentmethod to check if the object contains a value. We will getfalseas a result.
optional.isPresent(); // false