JavaHow to use Optional in Java

How to use Optional in Java

Java Developer Tutorials

An Optional object in Java is a container object that can hold both empty and a non-null values. If an Optional object does contain a value, we say that it is present; if it does not contain a value, we say that it is empty. Here, we will take a look at the Optional class in Java and how it can be used to help improve your code. We will also look at some of the drawbacks of using the Optional keyword in Java and some best practices.

Jump to:

What is the Optional Type in Java?

Optional is a new type introduced in Java 8. It is used to represent a value that may or may not be present. In other words, an Optional object can either contain a non-null value (in which case it is considered present) or it can contain no value at all (in which case it is considered empty).

An Optional object can have one of the following possible states:

  • Present: The Optional object does not represent absence. A value is in the Optional object and it can be accessed by invoking the get() method.
  • Absent: The Optional object does represent the absence of a value; you cannot access its content with the get() method.

Why Do Developers Need Optional in Java?

Optional is generally used as a return type for methods that might not always have a result to return. For example, a method that looks up a user by ID might not find a match, in which case it would return an empty Optional object.

Optional can help reduce the number of null pointer exceptions in your code as well. It is not intended as a replacement for existing reference types, such as String or List, but, rather, as an addition to the Java type system.

How to Create an Optional Object in Java

There are several ways to create an Optional object in Java, including the static factory methods empty() and of(), which pertain to the Optional class. You can create an Optional object using the of() method, which will return an Optional object containing the given value if the value is non-null, or an empty Optional object if the value is null.

Programmers can also use the ofNullable() method, which will return an empty Optional object if the value is null, or an Optional object containing the given value if it is non-null. Finally, you can create an empty Optional object using the empty() method.

Once you have created an Optional object, you can use the isPresent() method to check if it contains a non-null value. If it does, you can use the get() method to retrieve the value. Developers can also use the getOrElse() method, which will return the value if it is present, or a default value if it is not.

Read: Introduction to Inner Classes in Java

The Java isPresent and ifPresent Methods

Developers can take advantage of the isPresent method to check if an Optional object is empty or non-empty. The ifPresent method, meanwhile, can check if a particular Optional object is non-empty. The following code example illustrates how you can work with the ifPresent and isPresent methods in Java:

import java.util.Optional;
   public class OptionalDemo {  
      public static void main(String[] args) {
         Optional obj1 = Optional.of
         ("This is a sample text"); 
         Optional obj2 = Optional.empty();
         if (obj1.isPresent()) {          
            System.out.println
            ("isPresent method called on obj1 returned true");
         }       
    obj1.ifPresent(s -> System.out.println
   ("ifPresent method called on obj1"));
    obj2.ifPresent(s -> System.out.println
    ("ifPresent method called on obj2 "));
   }
}

In the above code example, we first check to see if two Optional object exists, using the isPresent() method. We assigned a value to obj1, so it will print out the string “This is a sample text”. obj2, however, was assigned an empty value, so it will print out nothing. We then print some more text to alert us that ifPresent was called on both of our Optional objects.

How to use Optional Objects in Java

There are a number of ways to create Optional objects. The most common way is to use the static factory method Optional.of(T), which creates an Optional object that is present and contains the given non-null value, as shown in the code snippet below:

Optional optional = Optional.of("value");

Additionally, we can create an empty Optional object using the static factory method Optional.empty, as shown in the code example below:

Optional optional = Optional.empty();

If we have a value that might be null, we can use the static factory method Optional.ofNullable(T) to create an Optional object that may or may not be present:

Optional optional = Optional.ofNullable(null);

Programmers can also use methods like ifPresent() and orElse() if you need to perform some action based on whether the optional has been set (if it contains a certain value) or if not, respectively:

Optional optionalString = Optional.of("value");
optionalString.ifPresent(s -> System.out.println(s));

Pros and Cons of using Optional Objects in Java

There are a few key pros to using Optional that Java developers should be aware of, including:

  • Optional can help to prevent NullPointerException errors by making it explicit when a variable may or may not contain a value. This can lead to cleaner and more readable code.
  • Optional provides several methods that can be used to safely work with data that may or may not be present.
  • Optional can be used as an ordinary class, which means that there is no need for special syntax for invoking methods or accessing fields.

Despite these benefits, there are a few potential downsides to using Optional as well:

  • Optional can add significant overhead to code execution time, as the Optional wrapper must be created and checked each time a variable is accessed.
  • Some developers find Optional confusing and difficult to work with, which can lead to more errors instead of fewer, and more development time and effort than usual as a result.

Read: Best Project Management Tools for Developers

Alternatives to Using Optional Objects in Java

There are a few alternatives to using Optional, such as using the null check operator (?.), using an if-else statement, or using a ternary operator.

The null check operator can be used to check if a value is null before accessing it. This can be done by using the ?. operator before the variable name. For example, the following Java code will check if the variable abc is null before accessing it:

if (abc != null) {
//Write your code here
}

If the variable abc is not null, the code inside the if statement will be executed. The if-else statement in the above code checks if the value is null before accessing it.

Best Practices for Using Optional

Below are some best practices to consider when using Optional in your Java code:

  • Use Optional to lower the amount of null pointer exceptions and account for times when returned values are empty or missing.
  • Do not use Optional as a stop-all for every type of null pointers. Coders still need to account method and constructor parameters that may also contain empty values.
  • Consider the context of your Optional objects; absent Optional values can mean different things, such as a particular value not being found versus no value at all being found. Account for these possibilities.
  • Use Optional as a return type and then retrieve its value if it is present or provide a different outcome if not.
  • Do not use Optional a parameter for methods or constructors. Using it in such  manner results in sloppy, hard to read, and difficult to maintain code.

Final Thoughts on Using Optional Objects in Java

Optional is a new feature in Java 8 that provides a way to handle null values in a more elegant way. The java.util.Optional class was introduced in Java 8 as a way to address the common problem of null pointer exceptions. By using Optional, programmers can avoid NullPointerExceptions and write cleaner code.

Want to learn more about objects and classes in Java? We recommend reading our tutorial What is an Abstract Class in Java as a next step.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories