What is the optional class in Java?
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 indexString 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 notnull, method returns anOptional, which describes the specified value. Otherwise, it returns an emptyOptional.public T get(): If a value is present, method returns it; otherwise, it throwsNoSuchElementException.public boolean isPresent(): The method returnstrueif there is a value present; otherwise, it returnsfalse.
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 nullOptional<String> checkForWord = Optional.ofNullable(sentence[9]);// Checking if value is present or not with isPresentif(checkForWord.isPresent()){// The get method returns the value held by the OptionalString word = checkForWord.get().concat("suffix");System.out.println(String.format("Word with suffix: %s", word));} elseSystem.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 sentencesentence[9] = "word ";// ofNullable method stores Optional with a value or an empty Optional if nullOptional<String> checkForWord = Optional.ofNullable(sentence[9]);// Checking if value is present or not with isPresentif(checkForWord.isPresent()){// The get method returns the value held by the OptionalString word = checkForWord.get().concat("suffix");System.out.println(String.format("Word with suffix: %s", word));} elseSystem.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 emptyOptionalinstance.static <T> Optional<T> of(T value): Method returns anOptionalwith the specified present non-nullvalue. If called on anull, the method throws aNullPointerException.
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 methodSystem.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
Optionalclass, you can visit the official documentation here.
Free Resources