What is the Optional.isPresent method in Java?
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.
What is the isPresent method of the Optional class?
The isPresent method is used to check if the Optional object contains a value.
public boolean isPresent()
Arguments
This method doesn’t take any arguments.
Return value
This method returns true if the Optional object contains a value. Otherwise, it returns false.
Code
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());}}
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> optional1 = Optional.empty();
- In line 6, we used the
ofmethod to get anOptionalobject of theIntegertype with value1.
Optional<Integer> optional2 = Optional.of(1);
- In line 7, we called the
isPresentmethod on theoptional1object. This object doesn’t have any value sofalsewill be returned.
optional1.isPresent();//false
- In line 8, we called the
isPresentmethod on theoptional2object. This object has1as the value so,truewill be returned.
optional2.isPresent();//true