Java11 introduced isEmpty
method java.util.Optional
package.
Optional is a container object that contains values or null.
It checks if an object does not exist and returns true.
Before java11, We have a isPresent()
method in Optional Class
isPresent()
is used to check an object that exists in Container and return true.
This only checks for Object that exists in Optional.
If you want to check object does not exist, you have to use a negative condition such as!Optional.isPresent in conditional statements. This is not readable and complex to understand. For example, To check string contains a null value, we have to write the below program.
package java11;
import java.util.Optional;
public class OptionalIsEmptyTest {
public static void main(String[] args) {
String name= "john";
String department= null;
System.out.println(Optional.ofNullable(name).isPresent()); // true
System.out.println(Optional.ofNullable(department).isPresent()); //false
System.out.println(Optional.ofNullable(name).isEmpty()); //false
System.out.println(Optional.ofNullable(department).isEmpty()); //true
// Check for department is null
if(!Optional.ofNullable(department).isPresent()){
System.out.println("Department is null");
}
// Check for name is not null
if(Optional.ofNullable(name).isPresent()){
System.out.println("Name is not null");
}
}
}
Output:
true
false
Department is null
Name is not null
For negative conditions, you have to use isPresent
with operator !.
The isEmpty
method is the opposite of the isPresent
method in java11.
Java11 Optional isEmpty method
isEmpty
method returns true if the value is null, else returns true.
Syntax:
public boolean isEmpty()
Here is a complete code example for the Optional isEmpty
method
package java11;
import java.util.Optional;
public class OptionalIsEmptyTest {
public static void main(String[] args) {
String name= "john";
String department= null;
System.out.println(Optional.ofNullable(name).isPresent()); // true
System.out.println(Optional.ofNullable(department).isPresent()); //false
System.out.println(Optional.ofNullable(name).isEmpty()); //false
System.out.println(Optional.ofNullable(department).isEmpty()); //true
// Check for department is null
if(Optional.ofNullable(department).isEmpty()){
System.out.println("Department is null");
}
// Check for name is not null
if(!Optional.ofNullable(name).isEmpty()){
System.out.println("Name is not null");
}
}
}