Java 11 - Optional isEmpty() method example

In this blog post, We are going to learn changes to Optional and primitive optional Classes in java 11 with examples.

Optional Classes IsEmpty Method

java.util.Optional class is introduced with java8.

In the java11 version, the isEmpty Method is introduced to the following classes.

This method checks and returns true if a value exists, else returns false.

Before Java11, If we want to check empty of Optional Classes, We will useOptional.isPresent().

with java11, This is a simplified and commonly used method like string and Collections empty check-in used with if conditional expression.

Syntax

public boolean isEmpty()

ExampleThe below example explains the following things

  • Optional.isEmpty(): Checking Optional is Empty or not .
  • OptionalInt.isEmpty() OptionalInt empty check Optional Integer for empty or not.
  • OptionalLong.isEmpty() OptionalLong empty check .
  • OptionalDouble.isEmpty() OptionalDouble empty check.
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;

public class OptionalDemo {

 public static void main(String[] args) {
  Optional<String> stringOptional=Optional.of("kiran");
  Optional<String> stringOptionalEmpty=Optional.empty();
  System.out.println("Optional isEmpty Example");
  System.out.println("1=" +stringOptional.isEmpty());
  System.out.println("2= "+stringOptionalEmpty.isEmpty());
  System.out.println("3= "+stringOptional.isPresent());
  System.out.println("4= "+stringOptionalEmpty.isPresent());

  OptionalInt intOptional = OptionalInt.of(51);
  OptionalInt intOptionalEmpty= OptionalInt.empty();

  System.out.println("OptionalInt isEmpty Example");
  System.out.println("=" +intOptional.isEmpty());
  System.out.println("2= "+intOptionalEmpty.isEmpty());
  System.out.println("3= "+intOptional.isPresent());
  System.out.println("4= "+intOptionalEmpty.isPresent());

  OptionalLong longOptional = OptionalLong.of(15);
  OptionalLong longOptionalEmpty= OptionalLong.empty();

  System.out.println("OptionalLong isEmpty Example");
  System.out.println("1=" +longOptional.isEmpty());
  System.out.println("2= "+longOptionalEmpty.isEmpty());
  System.out.println("3= "+longOptional.isPresent());
  System.out.println("4= "+longOptionalEmpty.isPresent());

  OptionalDouble doubleOptional = OptionalDouble.of(53);
  OptionalLong doubleOptionalEmpty= OptionalLong.empty();

  System.out.println("OptionalDouble isEmpty Example");
  System.out.println("1=" +doubleOptional.isEmpty());
  System.out.println("2= "+doubleOptionalEmpty.isEmpty());
  System.out.println("3= "+doubleOptional.isPresent());
  System.out.println("4= "+doubleOptionalEmpty.isPresent());

 }

}

Output:

Optional isEmpty Example
1=false
2= true
3= true
4= false
OptionalInt isEmpty Example
=false
2= true
3= true
4= false
OptionalLong isEmpty Example
1=false
2= true
3= true
4= false
OptionalDouble isEmpty Example
1=false
2= true
3= true
4= false