In this article we will cover Java 8 Optional.

As the Optional documentation states, it's a container object which may or may not contain a non-null value. Google Guava library users may be already familiar with the Optional class since it was already included in the library.

The Optional goal is to correctly represent an eventually null value at an arbitrary application code location.

The usage of the Optional class will also lead to a lesser number of null pointer exceptions at application runtime. This assumption has lead to many discussions around the subject, since the Optional class will also throw an exception if we try to access its value while the value is null. The whole point of the Optional class is that developers will know that when they face an Optional - and consequently are forced to unwrap its value - they must account for the null value possibility (and of course, as it may already be clear, Optional also gives API developers a proper way of representing the null value possibility).

Let's see a comparison:

findUser returns a User instance

User findUser(Long userId);

If a developer is including some 3rd party API which contains the aforementioned findUser method, he may not immediately know what happens if he provides a userId that does not correspond to any user: will the method return a null reference? Will it throw an exception? Let's see the Optional variant of the same method:

findUser returns an Optional instance

Optional<User> findUser(Long userId);

Just by looking at the method signature it now becomes clear that the method may return an Optional containing a null value. Since we now have to explicitly unwrap the Optional contained instance, it's mandatory (and hard to forget or avoid) to account for the possibility of the wrapped value being a null reference.