Java 8 Optional Class with Examples

1. Overview

Java introduced a new class Optional in JDK 8. It is a public final class and used to deal with NullPointerException in Java application. You must import java.util package to use this class. It provides methods which are used to check the presence of a value for the particular variable.
The purpose of the class is to provide a type-level solution for representing optional values instead of using null references.

2. Advantages of Java 8 Optional

  1. Null checks are not required.
  2. No more NullPointerException at run-time.
  3. We can develop a clean and neat APIs.
  4. No more Boilerplate code
To get a deeper understanding of why you should care about the Optional class, take a look at the official Oracle’s article.

3. Optional Basic Example

The Optional.ofNullable() method returns a Non-empty Optional if a value present in the given object. Otherwise returns empty Optional. Optionaal.empty() method is useful to create an empty Optional object.
import java.util.Optional;

public class OptionalBasicExample {

    public static void main(String[] args) {

        Optional<String> gender = Optional.of("MALE");
        String answer1 = "Yes";
        String answer2 = null;

        System.out.println("Non-Empty Optional:" + gender);
        System.out.println("Non-Empty Optional: Gender value : " + gender.get());
        System.out.println("Empty Optional: " + Optional.empty());

        System.out.println("ofNullable on Non-Empty Optional: " + Optional.ofNullable(answer1));
        System.out.println("ofNullable on Empty Optional: " + Optional.ofNullable(answer2));
        
        // java.lang.NullPointerException
        System.out.println("ofNullable on Non-Empty Optional: " + Optional.of(answer2));
    }
}

4. Usage of Optional class API'S

4.1 isPresent() Optional class API

The isPresent() method returns an Optional with the specified present non-null value.
Example :
private static void isPresentOptionalAPI() {
  Optional<String> opt = Optional.of("Ramesh");
  System.out.println(opt.isPresent());
}

4.2 empty() Optional class API

An empty() static method returns an empty Optional instance. No value is present for this Optional.
Example :
// Returns an Optional with the specified present non-null value.
 private static void createEmptyOptionalObject() {
  Optional<String> empty = Optional.empty();
  System.out.println(empty.isPresent());

  // Optional object with the static of API:
  String name = "Ramesh";
  Optional.of(name);
 }

4.3 ifPresent() Optional class API

If a value is present, invoke the specified consumer with the value, otherwise, do nothing.
Example : 
private static void ifPresentOptionalAPI() {
 // The ifPresent API enables us to run some code on the wrapped value if it is
 // found to be non-null.
 // Before Optional, we would do something like this:
 String name = "Ramesh";
 if (name != null) {
  System.out.println(name.length());
 }

 Optional<String> opt = Optional.of("Ramesh");
 opt.ifPresent(str -> System.out.println(str.length()));
}

4.4 orElse() Optional class API

Return the value if present otherwise returns other.
Example :
private static void orElseOptionalAPI() {
  // With orElse, the wrapped value is returned if it is present and the argument
  // given to
  // orElse is returned if the wrapped value is absent
  String nullName = null;

  // If a value is present, invoke the specified consumer with the value, otherwise
  // do nothing.
  //
  String name = Optional.ofNullable(nullName).orElse("Ramesh");
  System.out.println(name);
}

4.5 orElseGet Optional class API

Return the value if present, otherwise invoke other and return the result of that invocation.
Example :
private static void orElseGetOptionalAPI() {
 String nullName = null;
 String name = Optional.ofNullable(nullName).orElseGet(() -> "Ramesh");
 System.out.println(name);
}

4.6 orElseThrow Optional class API

Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.
Example :
private static void orElseThrowOptionalAPI() {
 String nullName = null;
 String name = Optional.ofNullable(nullName)
   .orElseThrow(IllegalArgumentException::new);
 System.out.println(name);
}

4.7 get() Optional class API

If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
Example :
private static void getOptionalAPI() {
 Optional<String> opt = Optional.of("Ramesh");
 String name = opt.get();
 System.out.println(name);
}

5. Complete Example for Reference

package com.ramesh.java8.classes;

import java.util.Optional;

public class OptionalClassExamples {

 public static void main(String[] args) {
  isPresentOptionalAPI();
  createEmptyOptionalObject();
  createEmptyOptionalObjectWithStaticAPI();
  ifPresentOptionalAPI();
  orElseOptionalAPI();
  orElseOptionalAPI();
  orElseGetOptionalAPI();
  orElseThrowOptionalAPI();
  getOptionalAPI();
 }

 // Returns an Optional with the specified present non-null value.
 private static void isPresentOptionalAPI() {
  Optional<String> opt = Optional.of("Ramesh");
  System.out.println(opt.isPresent());
 }

 // Returns an Optional with the specified present non-null value.
 private static void createEmptyOptionalObject() {
  Optional<String> empty = Optional.empty();
  System.out.println(empty.isPresent());

  // Optional object with the static of API:
  String name = "Ramesh";
  Optional.of(name);
 }

 private static void createEmptyOptionalObjectWithStaticAPI() {
  String name = "baeldung";
  Optional.of(name);
 }

 // If a value is present, invoke the specified consumer with the value, otherwise do
 // nothing.
 private static void ifPresentOptionalAPI() {
  // The ifPresent API enables us to run some code on the wrapped value if it is
  // found to be non-null.
  // Before Optional, we would do something like this:
  String name = "Ramesh";
  if (name != null) {
   System.out.println(name.length());
  }

  Optional<String> opt = Optional.of("Ramesh");
  opt.ifPresent(str -> System.out.println(str.length()));
 }

 // If a value is present, invoke the specified consumer with the value, otherwise do
 // nothing.
 private static void orElseOptionalAPI() {
  // With orElse, the wrapped value is returned if it is present and the argument
  // given to
  // orElse is returned if the wrapped value is absent
  String nullName = null;

  // If a value is present, invoke the specified consumer with the value, otherwise
  // do nothing.
  //
  String name = Optional.ofNullable(nullName).orElse("Ramesh");
  System.out.println(name);
 }

 // Return the value if present, otherwise invoke other and return the result of that
 // invocation.
 private static void orElseGetOptionalAPI() {
  String nullName = null;
  String name = Optional.ofNullable(nullName).orElseGet(() -> "Ramesh");
  System.out.println(name);
 }

 // Return the contained value, if present, otherwise throw an exception to be created
 // by the provided supplier.
 private static void orElseThrowOptionalAPI() {
  
  // This will throw exception
  String nullName = null;
  String name = Optional.ofNullable(nullName)
    .orElseThrow(IllegalArgumentException::new);
  System.out.println(name);
 }

 // If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException
 private static void getOptionalAPI() {
  Optional<String> opt = Optional.of("Ramesh");
  String name = opt.get();
  System.out.println(name);
 }

}

6. Conclusion

In this post, we have learned the usage of Optional class with simple examples and we have seen few methods of an Optional class with examples. The source code of this post is available on GithubNow to can read this post: Handle NullPointerException in Controller, Service and DAO Layer using Java 8 Optional Class.

    Comments