Over a million developers have joined DZone.

Using Optional to Specify Presence or Absence of a Value in Java

DZone's Guide to

Using Optional to Specify Presence or Absence of a Value in Java

What client logic needs to be written to find the answer to questions posed by Java interfaces?

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

Let’s say you have to use an interface to write some logic and you see the below interface definition.

public interface OrderService {
  Order findOrderWithId(long orderId);

What is the first thing that comes to your mind? Most probably it will be the question that, what happens if the order against the requested order id does not exist.

To find the answer you will either:

  • Check out the documentation on the interface (What if documentation is missing?), or
  • Look into the source code (What if the source code is not accessible?)

In any of the cases, the highest probability is that the interface will return a null Order.

The client logic that you will write against such an interface will be something like:

Order order = orderService.findOrderWithId(orderId);
if (order == null) throw new OrderNotFoundException();
... // do further processing

Most of the times the life of a developer is not easy. There are deadlines that you have to meet and under delivery pressure you may forget to add that null check if (order == null). And then you may see the dreaded NullPointerException when:

  • you run your unit tests (give a pat on your back for writing unit tests), or
  • your code is being tested by a QA (thank the QA for catching the bug in code), or
  • in the worst case when your code is running in production.

Representing the Possibility of Absence of a Value Using Optional

This is where Optional comes to rescue. It has been part of the Google’s Guava libraries for long. It has also recently been included in Java 8. Let’s try to re-write the interface using the Java 8’s version of Optional.

public interface OrderService {
  Optional<Order> findOrderWithId(long id);

Now if you use this interface to write some logic, you will observe that the return type itself is telling you that it may or may not be present. 

Let’s see how a client code against such an interface will look like. The below code is intentionally made verbose for the purpose of illustration. A more concise version will also follow.

Optional<Order> orderOptional = orderService.findOrderWithId(orderId);
if (!orderOptional.isPresent()) throw new OrderNotFoundException();
Order order = orderOptional.get(); 
... // do further processing

Note that the client code against interface to call an get() on the Optional to get the object which also forces the writer of client code to think about and handle the cases then value is not present. You can useisPresent() to check the presence or absence of a value.

A more concise version of the above code will be.

Order order = orderService.findOrderWithId(orderId)
... // do further processing

There are multiple factory methods like Optional.of(T value)Optional.ofNullable(T value) andOptional.empty() which can used on the producer side. On the consumer side instance methods likeget()orElse(T other)orElseGet(Supplier<? extends T> other) andorElseThrow(Supplier<? extends X> exceptionSupplier) can be used.


Use Optional to represent the absence or presence of a value. Use it to specify return types when designing interfaces or APIs. Its usage gives the following advantages:

  • The code becomes the documentation for any client using the code.
  • The client code becomes less error-prone and can avoid NullPointerExceptions due to negligence.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

java 8 ,optional ,java 8 functional programming

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}