In the previous tutorial about NullPointerException in Java, I have presented to you some cases where NPE can occur and how to deal with them to avoid. From Java 8, we have another way to avoid NullPointerException, that will use the Optional object. What is it? In this tutorial, we will learn about it together.
OK, let’s get started …
The Optional object is a generic object, which is a container for an object reference. This means that you declare a variable reference to an object, which may or may not have been initialized, and Optional object will contain this variable.
We can see Optional as a stream containing 0 or 1 element as an object reference, 0 if our object reference is null, 1 if our object reference has already been initialized.
This will ensure that when you use our reference variable through the Optional object, the return value is managed by the Optional object and therefore the value of this reference variable will never be null.
Now, I will take an example for you to imagine how to use the object Optional!
Suppose, you have a method used to derive a student’s birthday based on the id you pass on, after handling some business logic, this method returns null. Specifically, the method is as follows:
1 2 3 4 |
public Date getDateOfBirth(int studentId) { // Do something return null; } |
Now, I will use this method and unfortunately it returns null and I get NPE.
In this case, we can use the Optional object to handle the NullPointerException as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava; import java.util.Date; import java.util.Optional; public class Example { public Date getDateOfBirth(int studentId) { // Do something return null; } public static void main(String[] args) { Example e = new Example(); Optional<Date> date = Optional.ofNullable(e.getDateOfBirth(1)); date.ifPresent(d -> System.out.println(d.getDate())); } } |
In this example, we initialized an Optional object containing a variable that references the Date data type, which can be null depend on the value of the getDateOfBirth() method.
And in the code below, I use the ifPresent() method of the Optional object with the Lambda Expression to print the date in case this reference variable is not null.
Try running this example, you will see no more NPE appear.