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.
empty() methodThe empty method is used to get the empty instance of the OptionalInt class. The returned object does not have a value.
public static OptionalInt empty()
This method does not take any arguments.
This method returns an OptionalInt object with an empty value.
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());}}
In the code above:
Line 1: We imported the OptionalInt class.
import java.util.OptionalInt;
Line 5: We used the empty method to get an empty OptionalInt object. The returned object doesn’t have any value.
OptionalInt optional = OptionalInt.empy();
Line 7: We printed the created OptionalInt object.
System.out.println("OptionalInt: " + optional); // OptionalInt.empty
Line 8: We used the isPresent method to check if the object contains a value. We will get false as a result.
optional.isPresent(); // false