What is the OptionalLong.empty method in Java?
Overview
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.
The empty() method
The empty() method is used to get the empty instance of the OptionalLong class. The returned object doesn’t have any value.
Syntax
public static OptionalLong empty()
Arguments
This method doesn’t take an argument.
Return value
This method returns an OptionalLong object with an empty value.
Code
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());}}
Explanation
In the code above:
-
Line 1: We imported the
OptionalLongclass.
import java.util.OptionalLong;
-
Line 5: We used the
emptymethod to get an emptyOptionalLongobject. The returned object doesn’t have any value.
OptionalLong optional = OptionalLong.empty();
-
Line 7: We printed the created
OptionalLongobject.
System.out.println("OptionalLong: " + optional); // OptionalLong.empty
-
Line 8: We used the
isPresentmethod to check if the object contains a value. We will getfalseas a result.
optional.isPresent(); // false