Java 8 Optional Class

In Java 8, we have a newly introduced Optional class in java.util package. This class is introduced to avoid NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException. In this guide, we will see how to work with Optional class and the usage of various methods of this class.

Before we see the example of Optional class, lets see what happens when we don’t use Optional class and do not perform null check.

Java Example: Without using Optional class

In this example, we didn’t assign the value to the String str and we are trying to get the substring out of it. Since there is no value present in the str, the program is throwing NullPointerException.

Solution: Using Optional Class

Optional.ofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional.
We can check whether the returned Optional value is empty or non-empty using the isPresent() method.

Example: Optional isPresent() vs ifPresent() methods

In the above example, we have seen that by using isPresent() method we can check whether the particular Optional object(or instance) is empty or no-empty.
There is another method present in the Optional class, which only executes if the given Optional object is non-empty, the method is ifPresent(). Lets see an example to understand the difference.