logo

Optional Class


Show

A new way of optional class as isEmpty() to check if the value is available is introduced in Java 11. isEmpty() gives back false if value is available(present) otherwise true.

It can be used as another way of isPresent() method that needs to be invalidated to check if the value is not available.

Examine the below given example:

ApiTester.java

import java.util.Optional;

public class APITester {
   public static void main(String[] args) {
      String name = null;

      System.out.println(!Optional.ofNullable(name).isPresent());
      System.out.println(Optional.ofNullable(name).isEmpty());

      name = "Joe";
      System.out.println(!Optional.ofNullable(name).isPresent());
      System.out.println(Optional.ofNullable(name).isEmpty());
   }
}

Output

true
true
false
false