Short Java 8 Optional Tutorial

If you’ve been programming with Java for some time, I am quite sure that you’ve heard of or first-hand experienced the NullPointerException.
A NullPointerException occurs when the programmer (you..) try to perform some operation on a variable that hasn’t been assigned any value – hence, it is null.

The Java 8 Optional class provide a neat way to avoid NullPointerExceptions, by forcing the method to return an object of type Optional instead of possible null values.

In this article I’ll explain basic usage of the Optional class, and our example will be built around a repository, which fetches objects of type String from a database.

The repository consists of two methods – regularReturnMethod() and optionalReturnMethod(). The code sceleton looks like this:

As you can see, both methods accepts exactly one parameter – an integer. We’re assuming that this id is used to perform lookups in our imaginary database.

If there exists an entity in the database with the provided id, the regularReturnMethod will return an object of type String – just as expected.
The optionalReturnMethod however, will return an object of type Optional. The returned Optional will contain the String object.

Now, what if it doesn’t exist an entity in the database with the provided id?
The regularReturnMethod will have to return null – while the optionalReturnMethod can still return an object of type Optional. The only difference is that this time the Optional object is empty.

Let’s expand a little bit further on our example, before diving more into the details of the Optional class.

Notice that I’ve provided a private helper method findById. This method will always return null, and will help us understand how Optionals work.

In our new implementation, the optionalReturnMethod return Optional.ofNullable(findById(id)).

There are two possible outcomes of the static method ofNullable:

  • If the findById() method returns null, it will return an empty Optional.
  • If the findById() method does return a String, it will return an Optional object which contain a String object.

 

Processing Java Optionals

To process the RepositoryExample class, we need a client class to which will call the optionalReturnMethod.

In your client class, you’ll first want to instantiate an instance of RepositoryExample.

RepositoryExample repo = new RepositoryExample();

Now, you have two ways to fetch a String object from that repository.

To fetch a regular String object, you simply write

String string = repo.regularReturnMethod(1);

Suppose you want to check the length of that String. What will happen?

string.length() // NullPointerException! findById() returns null!

To get rid of that nasty NullPointerException, let’s use Java Optional instead:

Optional<String> optional = repositoryExample.optionalReturnMethod(1);

Then we check whether it is empty or not:

if(optional.isPresent()) { System.out.println(optional.get().length()); }

There are two method you should be aware of:

  • isPresent() – this checks whether the Optional has a value present.
  • get() – this will return the value the Optional objects currently holds.

Note that Java has made a leap towards functional programming, so you can also perform this check functional style:

optional.ifPresent(val -> System.out.println(val.length()));

As the title said, this article is only a short introduction to the Java 8 Optional class. Please refer to the official documentation for more information. 🙂

Quick tip: If you wish to expand your Java skill-set and become an advanced Java developer, I highly recommend you to get yourself a copy of the best-selling Effective Java, by Joshua Bloch!

You may also like...

Leave a Reply

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