Java 11

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 program −

Java11Optional.java

import java.util.Optional;

public class Java11Optional {
	
	public static void main(String[] args) {	
	      // 1. Check non-null value is present 
	      String name = "Elavarasan";
	      System.out.println(Optional.ofNullable(name).isPresent());
	      System.out.println(Optional.ofNullable(name).isEmpty());
	      // 2. Check string has null/empty value
	      name = null;
	      System.out.println(Optional.ofNullable(name).isPresent());
	      System.out.println(Optional.ofNullable(name).isEmpty());
	}
}

Output:

true
false
false
true

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs