What is the Optional.isPresent method in Java?

In Java, the Optional object is a container object that may or may not contain a value. Using the Optional object’s isPresent method, we can replace the multiple null check.

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

Read more about the Optional class here.

What is the isPresent method of the Optional class?

The isPresent method is used to check if the Optional object contains a value.

public boolean isPresent()

Arguments

This method doesn’t take any arguments.

Return value

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

Code

The code below demonstrates how to use the isPresent method.

import java.util.Optional;
class OptionalIsPresentExample {
public static void main(String[] args) {
Optional<Integer> optional1 = Optional.empty();
Optional<Integer> optional2 = Optional.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 Optional class.
import java.util.Optional;
  • In line 5, we used the empty method to get an empty Optional object of the Integer type. The returned object doesn’t have any value.
Optional<Integer> optional1 = Optional.empty();
  • In line 6, we used the of method to get an Optional object of the Integer type with value 1.
Optional<Integer> optional2 = Optional.of(1);
  • In line 7, we called the isPresent method on the optional1 object. This object doesn’t have any value so false will be returned.
optional1.isPresent();//false
  • In line 8, we called the isPresent method on the optional2 object. This object has 1 as the value so, true will be returned.
optional2.isPresent();//true

Free Resources