Java 8 Optional Usage and Best Practices

According to the Oracle documentation, an Optional is a container object that may or may not contain a non-null value. It was introduced in Java 8 to cure the curse of NullPointerExceptions. In essence, Optional is a wrapper class that contains a reference to some other object. In this context, an object is just a pointer to a memory location and it can as well point to nothing. Another way to look at it is as a way to provide a type-level solution for representing optional values instead of null references.

Life Before Optional

Before Java 8, programmers would return null instead of Optional. There were a few shortcomings with this approach. One was that there wasn’t a clear way to express that null might be a special value. By contrast, returning an Optional is a clear statement in the API that there might not be a value in there. If we wanted to make sure that we won't get a null pointer exception, then we would need to do explicit null check for each reference, as shown below, and we all agree that’s a lot of boilerplate.