Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.
##working code
package com.example;
import java.util.Optional;
public class OptionalMethodInjava {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Old WAY BEFORE JAVA 8
// String str = "Values is there"; // // if (str == null) { // System.out.println("value is null"); // } else { // System.out.println(str); // }
// After BEFORE JAVA 8
String str = "Values is there";
Optional<String> optional = Optional.of(str);
System.out.println(optional.get());
System.out.println("isEmpty()--" + optional.isEmpty());
System.out.println("isPresent()--" + optional.isPresent());
System.out.println("orElse--" + optional.orElse("No values Found"));
}
}
##Output


