Optional class in Java 8 with example

Optional Class in Java 8

An often annoying problem that most Java developers face in their code is the NullPointerException. This exception is thrown whenever we try to access an object that doesn’t exist in memory or in other words when trying to perform operations on a reference that points to nothing i.e. null.

Here is a simple code that generates NullPointerException.


This program is quite straight forward, so we know that exception is likely to occur. But what if the value we use comes from some other program / method or if it comes as a result of some operation. In this case it is difficult to infer the occurrence of NullPointerException. So we can avoid the exception by having a null check on the reference as below,


Java 8 introduced a new class called java.util.Optional<T> which can be used to handle NullPointerException efficiently. It acts as a single-value container that either contains a value or doesn’t (it is then said to be “empty”). If a value is present, the method isPresent() will return true and get() will return the contained value. Here is a pictorial representation.

Optional Class in Java 8

Now we can write the same program using Optional class as below,


Here I have written a lambda expression inside ifPresent() method. If you are not clear with the syntax I recommend you to read my post on Lambda Expressions. Also to understand further code snippets in the article, I suggest you to have an understanding of method references in Java.

Creating Optional objects

Here we will see some of the ways to create an Optional object.

To create an empty Optional,

Optional<String> str = Optional.empty();


To create an Optional object with non-null value,

Optional<String> str = Optional.(value); // throws NullPointerException if value is null


To create an Optional object that may hold a null value,

Optional<String> str = Optional.ofNullable(value);


Do Something If a Value Is Present

If you have an Optional object, you can access the methods available to explicitly deal with the presence or absence of values.  As we already seen, instead of doing a null check we can use ifPresent() method as below,


You can also use the isPresent() method to find out whether a value is present in an Optional object

The get() method returns the value contained in the Optional object, if it is present. Otherwise, it throws a NoSuchElementException.

Default Values and Actions

Quite often we do the following to have default values set for the object in case a value is not present.

String str = (anotherString == null ? “” : anotherString) ;

Using an Optional object, you can rewrite this code by using the orElse() method, which provides a default value if Optional is empty

Optional<String > anotherString;

String substring = anotherString.orElse(“”);

Similarly, you can use the orElseThrow() method, which instead of providing a default value, if Optional is empty, throws an exception.

Optional<String > anotherString;

String substring = anotherString. orElseThrow (IllegalStateException::new));

Using the filter and map Method

The filter method takes a predicate (condition) as an argument. If a value is present in the Optional object and it matches the predicate, the filter method returns that value; otherwise, it returns an empty Optional object. If a value is present in the Optional object, the map method takes a function as an argument, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.  Let us see the usage.


Here the map method extracts the person’s age and the filter method returns the value if the age is greater than 18.


In this article, we have seen the usage of Optional class in Java 8. The purpose of Optional class is not to replace every single null reference in your code base but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.