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

Explanation

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
    

Free Resources