Optional class in Java 8

Hey there!

Welcome to ClearUrDoubt.com.

In this post, we will look at the demonstration of Optional<T> class in Java 8.

Optional is introduced in Java 8 mainly to provide a way to avoid Null Pointer Exceptions in the code. Instead of directly working on probably a null returning value, it’s better to use Optional instance to avoid NullPointerException. You can find the complete documentation here.

  • Optional class doesn’t have any constructors.
  • isPresent() method is used to check if the instance has a value.
  • get() method is used to retrieve the value. it will throw “NoSuchElementException” if there is no value.
  • of(T val) method is used to create Optional<T> instance – val must be a non-null value.
  • ofNullable(T val) method is used to create Optional<T> instance – if val is null, it returns an empty Optional.
  • orElse(T defaultVal) method is used to return T if present, otherwise it returns  defaultVal

 

Let’s look at a sample program:

Output:

Happy Learning :).

Please let me know in case of any queries.

Leave a Reply

Your email address will not be published.