What is the OptionalInt.isPresent method in Java?
Overview
In Java, the OptionalInt object is a container object
which may or may not contain an integer value.
The OptionalInt class is present in the java.util package.
The isPresent() method
The isPresent() method is used to check if the OptionalInt object contains a value.
Syntax
public boolean isPresent()
Arguments
This method doesn’t take an argument.
Return value
This method returns true if the OptionalInt object contains a integer value. Otherwise, false will be returned.
Code
The code below denotes how to use the isPresent method.
import java.util.OptionalInt;class OptionalIntIsPresentExample {public static void main(String[] args) {OptionalInt optional1 = OptionalInt.empty();OptionalInt optional2 = OptionalInt.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:
-
Line 1: We imported the
OptionalIntclass.
import java.util.OptionalInt;
-
Line 5: We used the
emptymethod to get an emptyOptionalIntobject. The returned object doesn’t have any value.
OptionalInt optional1 = OptionalInt.empty();
-
Line 6: We used the
ofmethod to get anOptionalIntobject with value1.
OptionalInt optional2 = OptionalInt.of(1);
-
Line 7: We called the
isPresentmethod on theoptional1object. This object doesn’t have any value, sofalsewill be returned.
optional1.isPresent();//false
-
Line 8: We called the
isPresentmethod on theoptional2object. This object has1as the value, sotruewill be returned.
optional2.isPresent();//true