English 中文(简体)
Java 11 - Optional Class
  • 时间:2024-09-17

Java 11 - Optional Class


Previous Page Next Page  

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;

pubpc class APITester {
   pubpc 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
Advertisements