Java 11 - Optional Class


Java 11 introduced new method to Optional class as isEmpty() to check if value is present. isEmpty() returns false if value is present otherwise true.

It can be used as an alternative of isPresent() method which often needs to negate to check if value is not present.

Consider the following 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
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements