In Java, an
OptionalLong
object is a container object which may or may not contain along
value. TheOptionalLong
class is present in thejava.util
package.
isPresent()
method of the OptionalLong
class?The isPresent()
method is used to check if an OptionalLong
object contains a value.
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
.
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());}}
In the code above:
OptionalLong
class.import java.util.OptionalLong;
empty()
method to get an empty OptionalLong
object. The returned object doesn’t have any value.OptionalLong optional1 = OptionalLong.empty();
of()
method to get an OptionalLong
object with value 1
.OptionalLong optional2 = OptionalLong.of(1);
isPresent()
method on the object optional1
. This object doesn’t have any value, so false
is returned.optional1.isPresent(); //false
isPresent()
method on the object optional2
. This object has 1
as the value, so true
is returned.optional2.isPresent(); //true