What is the OptionalDouble.empty method in Java?

In Java, the OptionalDouble object is a container object that may or may not contain a double value.

The OptionalDouble class is present in the java.util package.

The empty method is used to get the empty instance of the OptionalDouble class. The returned object doesn’t have any value.

Syntax

public static OptionalDouble empty()

Argument

This method doesn’t take any arguments.

Return value

This method returns an OptionalDouble object with an empty value.

Code

The code below denotes how to use the empty method.

import java.util.OptionalDouble;
class OptionalDoubleEmptyExample {
public static void main(String[] args) {
OptionalDouble optional = OptionalDouble.empty();
// print value
System.out.println("OptionalDouble : " + optional);
System.out.println("Has value: " + optional.isPresent());
}
}

Explanation

In the code above:

  • In line 1, we imported the OptionalDouble class.

  • In line 5, we used the empty method to get an empty OptionalDouble object. The returned object doesn’t have any value.

  • In line 7, we printed the created OptionalInt object.

  • In line 8, we used the isPresent method to check if the object contains a value. We will get false as a result.

Free Resources