What is the OptionalLong.isPresent() method in Java?
In Java, an
OptionalLongobject is a container object which may or may not contain alongvalue. TheOptionalLongclass is present in thejava.utilpackage.
What is the isPresent() method of the OptionalLong class?
The isPresent() method is used to check if an OptionalLong object contains a value.
Syntax
public boolean isPresent()
This method doesn’t take any argument.
This method returns true if the OptionalLong object contains a long value. Otherwise, it returns false.
Code
The code below shows how to use the isPresent() method.
import java.util.OptionalLong;class OptionalLongIsPresentExample {public static void main(String[] args) {OptionalLong optional1 = OptionalLong.empty();OptionalLong optional2 = OptionalLong.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
OptionalLongclass.
import java.util.OptionalLong;
- In line 5, we used the
empty()method to get an emptyOptionalLongobject. The returned object doesn’t have any value.
OptionalLong optional1 = OptionalLong.empty();
- In line 6, we used the
of()method to get anOptionalLongobject with value1.
OptionalLong optional2 = OptionalLong.of(1);
- In line 7, we called the
isPresent()method on the objectoptional1. This object doesn’t have any value, sofalseis returned.
optional1.isPresent(); //false
- In line 8, we called the
isPresent()method on the objectoptional2. This object has1as the value, sotrueis returned.
optional2.isPresent(); //true