Optional Class

Optional Class is a new feature introduced in Java 8. This Optional class is present in java.util package. It helps one in writing a neat code without much use of null checks. By using Optional, we can determine the alternate values to return or the alternate code to run. In other words, to avoid abnormal termination, we use the Optional class. Optional is basically a container object which may or may not contain a non-null value. It is a public final class that deals with NullPointerException in Java application.

Declaration –

public final class Optional<T> extends Object

Some utility methods available in optional class are –

  • isPresent()
    • If a value is present, isPresent() will return true.
  • get()
    • It will return the value if isPresent() returns true.
  • orElse()
    • It returns a default value if value not present.
  • empty()
    • It returns an empty Optional instance.
  • filter()
    • If a value is present and the value matches a given predicate, it returns an Optional describing the value, otherwise returns an empty Optional.
  • equals()
    • Indicates whether some other object is “equal to” this Optional.
  • ofNullable()
    • It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
  • orElseGet()
    • It returns the value if present, otherwise invokes others, and returns the result of that invocation.
  • orElseThrow()
    • It returns the contained value, if present, otherwise throws an exception to be created by the provided supplier.
import java.util.Optional;

public class OptionalExample {
	public static void main(String args[]) {
		String[] str = new String[10];
		str[5] = "OptionalClass";
		
		//It returns an empty instance of Optional class
		Optional<String> empty = Optional.empty();
		
		//It returns a non-empty Optional
		Optional<String> value = Optional.of(str[5]);
		
		//If value is present, it returns Optional
		//If value is not present, it returns an empty Optional
		System.out.println(value.filter(
			(s) -> s.equals("ABC"))
		);
		
		//If value is present, it returns value of an Optional
		//If value is not present, it throws an NoSuchElementException
		System.out.println("Getting value: "+value.get());
		
		//It returns hashCode of the value
		System.out.println("Getting hashCode: "+value.hashCode());
		
		//It returns true if value is present, otherwise false
		System.out.println("Is value present: "+value.isPresent());
		
		//If value is present, it returns non-empty Optional
		//If value is not present, it returns an empty Optional
		System.out.println(Optional.ofNullable(str[5]));
		
		//It returns value if available, otherwise returns specified value
		System.out.println(+value.orElse("Value is not present"));
		
	}
}
Scroll to Top