What is the OptionalLong.isPresent() method in Java?

In Java, an 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.

What is the isPresent() method of the OptionalLong class?

The isPresent() method is used to check if an OptionalLong object contains a value.

Syntax

public boolean isPresent()

This method doesn’t take any argument.

This method returns true if the OptionalLong object contains a long value. Otherwise, it returns false.

Code

The code below shows how to use the isPresent() method.

import java.util.OptionalLong;
class OptionalLongIsPresentExample {
public static void main(String[] args) {
OptionalLong optional1 = OptionalLong.empty();
OptionalLong optional2 = OptionalLong.of(1);
System.out.println("Checking if optional1 has value : " + optional1.isPresent());
System.out.println("Checking if optional2 has value : " + optional2.isPresent());
}
}

Explanation

In the code above:

  • In line 1, we imported the OptionalLong class.
import java.util.OptionalLong;
  • In line 5, we used the empty() method to get an empty OptionalLong object. The returned object doesn’t have any value.
OptionalLong optional1 = OptionalLong.empty();
  • In line 6, we used the of() method to get an OptionalLong object with value 1.
OptionalLong optional2 = OptionalLong.of(1);
  • In line 7, we called the isPresent() method on the object optional1. This object doesn’t have any value, so false is returned.
optional1.isPresent(); //false
  • In line 8, we called the isPresent() method on the object optional2. This object has 1 as the value, so true is returned.
optional2.isPresent(); //true

Free Resources