What is the OptionalInt.empty method in Java?
In Java, the OptionalInt object is a container object that may or may not contain an integer value.
The
OptionalIntclass is present in thejava.utilpackage.
The empty() method
The empty method is used to get the empty instance of the OptionalInt class. The returned object does not have a value.
Syntax
public static OptionalInt empty()
Arguments
This method does not take any arguments.
Return value
This method returns an OptionalInt object with an empty value.
Code
The code below shows how to use the empty method.
import java.util.OptionalInt;class OptionalIntEmptyExample {public static void main(String[] args) {OptionalInt optional = OptionalInt.empty();// print valueSystem.out.println("OptionalInt : " + optional);System.out.println("Has value: " + optional.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 optional = OptionalInt.empy();
-
Line 7: We printed the created
OptionalIntobject.
System.out.println("OptionalInt: " + optional); // OptionalInt.empty
-
Line 8: We used the
isPresentmethod to check if the object contains a value. We will getfalseas a result.
optional.isPresent(); // false