Optional in Java 8

In this article, we will discuss about the new Optional feature added in Java 8.

Also, we will see example of how Optional makes the code more readable and avoids Null Pointer Exceptions.
 
java 8 optional
 

What is Optional in Java 8 ?

 
Java 8 added a new class java.util.Optional that provides a way to handle situations where a value may or may not be present.

Optional is a container object which may or may not contain a not null value.

 

Why use Optional in Java ?

 
We normally assign null to a variable to indicate that it doesn’t have a value.

However, this frequently results in a NullPointerException if we to try to find value by dereferencing.

To prevent this, we normally add frequent NULL checks in our code to check if a variable is not empty before we use it in our program.

Optional provides a better approach to handle such situations.

 

How to create an Optional object in Java?

 
Optional class does not define any constructors. Instead, we can use one of following methods to create an instance.
 

Optional.empty

 
We can create an empty Optional by using the Optional.empty() method:


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

 

Optional.ofNullable

 
Optional.ofNullable() method allows creating an optional that can accept null.


Integer x = null;
Optional<Integer> optional = Optional.ofNullable(x);

 

Optional.of

 
We can create an optional with a specified value using Optional.of() as follows :


Integer y = null;
Optional<Integer> optional = Optional.of(y);

 

Accessing values from an Optional object

 

isPresent() and get()

 
We can call get() method to obtain a value present in an Optional instance. But if doesn’t contain a value, the method would throw NoSuchElementException. Therefore, we should first determine if a value is present using isPresent() method and then call get() method if value is available.


        Optional<String> emptyString = Optional.empty();
        
        if(emptyString.isPresent())
          System.out.println(emptyString.get());
        else
          System.out.println("emptyString has no value");

Here, we have the overhead of calling two methods to access a value. We can instead use methods like orElse(), orElseGet() or orElseThrow() that combine checking the value with retrieving it.
 

orElse(defaultValue)

 
This method returns the value if present, otherwise returns the default value provided as parameter.


    Optional<String> emptyString = Optional.ofNullable(null);

    System.out.println(emptyString.orElse("Empty String"));

 

Output:

 
Empty String
 

orElseGet(getFunc)

 
This method returns the value if present, otherwise returns the value obtained from getFunc.


    Optional<Employee> optionalEmp = Optional.empty();

    Supplier<Employee> defaultEmp = new Supplier<Employee>() {

      @Override
      public Employee get() {
        Employee emp = new Employee();
        emp.setName("John Doe");
        return emp;
      }
    };

 

Output:

 
John Doe

 

orElseThrow(excFunc)

 
This method returns the value if present, otherwise throws the exception generated by excFunc.


    Optional<Employee> optionalEmp = Optional.empty();
    optionalEmp.orElseThrow(NoSuchElementException::new);

 

Output:

 
Exception in thread “main” java.util.NoSuchElementException

 

Summary

 
Optional class forces us to deal with absense of a value. This helps prevent Null pointer exceptions at runtime.

JDK 8 also provides OptionalLong, OptionalInt and OptionalLong that are designed specifically for double, int and long values respectively.

 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

3 comments

  1. I’m still waiting for an epiphany on why an isPresent() check saves anything over a null check. The orElse* methods are a definite plus though

  2. This is a very enticing way of using Optionals. Thanks. Is there a way to use Optionals in Android development with Java 8?

  3. Ben C. R. Leggiero

    Lazy Initialization is much more elegant, IMHO. Unfortunately there aren’t any built-in ways to do this, so I usually write my own generic Lazy class.

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: