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 OptionalInt class is present in the java.util package.

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 value
System.out.println("OptionalInt : " + optional);
System.out.println("Has value: " + optional.isPresent());
}
}

Explanation

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