What is Optional.isEmpty in Java?

The isEmpty method of the Optional class is an object method that is used to check if the object contains a value or not. The method returns true if a value is not present. Otherwise, it returns false.

To learn what the Optional class is, refer to this Answer.

How to import the Optional class

The Optional class is defined in the java.util package. Use the import statement below to import the Optional class.

import java.util.Optional;

Syntax

public boolean isEmpty()

Parameters

This method takes no parameters.

Return value

The method returns true if a value is not present. Otherwise, it returns false.

Code

In the code below, we create an instance of the Optional class using the method ofNullable for different values and to check the behavior of the isEmpty() method.

Refer to this shot to learn more about the ofNullable method.

import java.util.Optional;
class main {
public static void main(String[] args) {
String test = "hello-educative";
Optional<String> stringOptional = Optional.ofNullable(test);
System.out.println("The isEmpty() method returns " + stringOptional.isEmpty() + " when the Optional object has a string value");
test = "";
stringOptional = Optional.ofNullable(test);
System.out.println("The isEmpty() method returns " + stringOptional.isEmpty() + " when the Optional object has an empty string value");
test = null;
stringOptional = Optional.ofNullable(test);
System.out.println("The isEmpty() method returns " + stringOptional.isEmpty() + " when the Optional object has no value");
}
}

Explanation

Example 1

In the first example, we create an Optional object from a non-empty string. The method isEmpty() returns false, indicating that the object contains a value.

Example 2

In the second example, we create an Optional object from an empty string. The method isEmpty() returns false, which indicates that the object contains a value and means an empty string is a valid string.

Example 3

In the third example, we create an Optional object from a null value. As the value passed is null, the method ofNullable replaces it with an empty Optional. Hence, the method isEmpty() returns true, indicating that the object doesn’t contain any value.

Free Resources