In Java, the Optional object is a container object that may or may not contain a value. Using the Optional object’s isPresent method, we can replace the multiple null check.
The
Optionalclass is present in thejava.utilpackage.
Read more about the
Optionalclass here.
isPresent method of the Optional class?The isPresent method is used to check if the Optional object contains a value.
public boolean isPresent()
This method doesn’t take any arguments.
This method returns true if the Optional object contains a value. Otherwise, it returns false.
The code below demonstrates how to use the isPresent method.
import java.util.Optional;class OptionalIsPresentExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.empty();Optional<Integer> optional2 = Optional.of(1);System.out.println("Checking if optional1 has value : " + optional1.isPresent());System.out.println("Checking if optional2 has value : " + optional2.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> optional1 = Optional.empty();
of method to get an Optional object of the Integer type with value 1.Optional<Integer> optional2 = Optional.of(1);
isPresent method on the optional1 object. This object doesn’t have any value so false will be returned.optional1.isPresent();//false
isPresent method on the optional2 object. This object has 1 as the value so, true will be returned.optional2.isPresent();//true