Trusted answers to developer questions

What is the ​optional class in Java?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The Optional class in Java is a container that can hold, at max, one value and gracefully deals with null values. The class was introduced in the java.util package to remove the need for multiple null checks to protect against the dreaded NullPointerExceptions during run-time.

The code below shows a situation where the Optional class would come in handy:

class OptionallessExample {
public static void main(String[] args) {
String[] sentence = new String[10];
// Concatenating a suffix to a non existent word in the 9th index
String word = sentence[9].concat("suffix");
System.out.println(String.format("Word with suffix: %s", word));
}
}

Although the example above is pretty straightforward, the NullPointerException often hinders code execution in Java. The Optional class has several useful methods that help prevent this.

In the code below, we will fix the problem above with the help of the following Optional class methods:

  • public static <T> Optional<T> ofNullable(T value): If the value is not null, method returns an Optional, which describes the specified value. Otherwise, it returns an empty Optional.
  • public T get(): If a value is present, method returns it; otherwise, it throws NoSuchElementException.
  • public boolean isPresent(): The method returns true if there is a value present; otherwise, it returns false.
import java.util.Optional;
class OptionalExample {
public static void main(String[] args) {
String[] sentence = new String[10];
// ofNullable method stores Optional with a value or an empty Optional if null
Optional<String> checkForWord = Optional.ofNullable(sentence[9]);
// Checking if value is present or not with isPresent
if(checkForWord.isPresent()){
// The get method returns the value held by the Optional
String word = checkForWord.get().concat("suffix");
System.out.println(String.format("Word with suffix: %s", word));
} else
System.out.println("No word is present to append suffix to.");
}
}

But how would the code have responded if the 9th index of sentence hadn’t been null? Let’s take a look at the code​ below:

import java.util.Optional;
class OptionalExample {
public static void main(String[] args) {
String[] sentence = new String[10];
// Storing a value in the 9th index of sentence
sentence[9] = "word ";
// ofNullable method stores Optional with a value or an empty Optional if null
Optional<String> checkForWord = Optional.ofNullable(sentence[9]);
// Checking if value is present or not with isPresent
if(checkForWord.isPresent()){
// The get method returns the value held by the Optional
String word = checkForWord.get().concat("suffix");
System.out.println(String.format("Word with suffix: %s", word));
} else
System.out.println("No word is present to append suffix to.");
}
}

Two other methods of the Optional class worth noting:

  • static <T> Optional<T> empty(): Method returns an empty Optional instance.
  • static <T> Optional<T> of(T value): Method returns an Optional with the specified present non-null value. If called on a null, the method throws a NullPointerException.

Let’s put these methods to use in the following example:

import java.util.Optional;
class OptionalExample {
public static void main(String[] args) {
// using the of method to create an Optional instance with value "B+"
Optional<String> grade = Optional.of("B+");
String opt1 = "Not null";
String opt2 = null;
System.out.println("Non-Empty Optional: " + grade);
System.out.println("Value of Non-Empty Optional: " + grade.get());
// Printing an empty instance of Optional with the empty method
System.out.println("Empty Optional: " + Optional.empty());
System.out.println("ofNullable on Non-Empty Optional: " + Optional.ofNullable(opt1));
System.out.println("ofNullable on Empty Optional: " + Optional.ofNullable(opt2));
if(Optional.ofNullable(opt1).isPresent()){
System.out.println("of on Non-Empty Optional: " + Optional.of(opt1));
}
if(Optional.ofNullable(opt2).isPresent()){
System.out.println("of on Empty Optional: " + Optional.of(opt2));
}
}
}

To learn more about the Optional class, you can visit the official documentation here.

RELATED TAGS

java
class
optional
null

CONTRIBUTOR

Anusheh Zohair Mustafeez
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?