In Java, the OptionalLong
object is a container object which may or may not contain a long
value.
The OptionalLong
class is present in the java.util
package.
empty()
methodThe empty()
method is used to get the empty instance of the OptionalLong
class. The returned object doesn’t have any value.
public static OptionalLong empty()
This method doesn’t take an argument.
This method returns an OptionalLong
object with an empty value.
The code below denotes how to use the empty
method.
import java.util.OptionalLong;class OptionalLongEmptyExample {public static void main(String[] args) {OptionalLong optional = OptionalLong.empty();// print valueSystem.out.println("OptionalLong : " + optional);System.out.println("Has value: " + optional.isPresent());}}
In the code above:
Line 1: We imported the OptionalLong
class.
import java.util.OptionalLong;
Line 5: We used the empty
method to get an empty OptionalLong
object. The returned object doesn’t have any value.
OptionalLong optional = OptionalLong.empty();
Line 7: We printed the created OptionalLong
object.
System.out.println("OptionalLong: " + optional); // OptionalLong.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