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 thejava.util
package. Read more aboutOptional
class here.
public static <T> Optional<T> empty()
This method doesn’t take any argument.
This method returns an Optional
object with an empty value.
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());}}
In the code above:
Optional
class.import java.util.Optional;
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();
Optional
object.System.out.println("Optional: " + optional); // Optional.empty
isPresent
method to check if the object contains a value. We will get false
as a result.optional.isPresent(); // false