Optional class — An intuitive approach for handling NullPointerException in java

Dsforgood
4 min readMar 1, 2022

--

Hello readers and developers in this article we are going to discover and learn about Optional class in Java. Optional class was introduced in java 8 and is used to deal with NullPointerException. In this article we will also see some of the practical coding examples. So without wasting your precious time let us start by understanding what is NullPointerException.

NullPointerException a brief intro

If you are a java developer you need no further introduction about the much hated NullPointerException. NullPointerException is a common exception in java which occurs when we try to access a variable pointing to a null reference.

In the below code snippet String s1 is pointing to null and we are trying to use charAt() method on it.

The above code will lead to a NullPointerException. To solve this we need to add additional if conditions and in it we need to check for null every time when we use the variable like shown below.

Now let us give you a brief tour of optional class.

Optional class a brief tour

Optional class is a public final class which belongs to util package in java. Theoretically speaking optional class is a container that can hold both null and not-null values. By using methods in the optional class we can check for existence of null values. The purpose of the class is to provide a type-level solution for representing optional values instead of null references. Now let us discuss the different ways to create optional objects.

Ways to create Optional Objects

1, Using empty()

To create an empty Optional object, we simply need to use its empty() static method like shown below,

In the above code we are using the isPresent() method of the optional class to check whether any value is present in the Optional object.

2, Using of()

We can also create an Optional object with the static method of() like shown below.

One thing to note in the above code is the argument passed to the of() method can’t be null. Otherwise, we’ll get a NullPointerException.

3, Using the ofNullable()

In case we expect some null values, we can use the ofNullable() method like shown below,

In the above code, if we pass in a null reference, it doesn’t throw an exception but rather returns an empty Optional object.

Now let us take a look at some of the methods of Optional class

Useful methods of Optional class

· IsPresent(): It returns true if there is a value present, otherwisereturns false.

· get(): If a value is present in this Optional Object, returns the value, otherwise throws NoSuchElementException.

· isEmpty(): returns true if the Optional object is empty else return false.

· ifPresent(): This method enables us to run some code on the wrapped value if it’s found to be non-null.

· orElse():This method is used to retrieve the value wrapped inside an Optional instance. It takes one parameter, which acts as a default value. This method returns the wrapped value if it’s present, and its argument otherwise.

· orElseGet(): This method is similar to orElse(). However, instead of taking a value to return if the Optional value is not present, it takes a supplier functional interface, which is invoked and returns the value.

· filter(): In this method, If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.

· map(): in this method, If a value is present, apply the provided function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

  • or(): This is a method for providing a supplier that creates an alternative Optional.
  • ifPresentOrElse() : It is a method that allows executing an action if the Optional is present or another action if not
  • stream(): This is a method for converting an Optional to a Stream

Now let us discuss more about optional classes.

Optional class when and where to use

We have seen many cases where optional is used incorrectly. It must be used as return type for methods. The optional should not be used as parameters of methods. Also remember the fact that Optional is a final class. Optional when used as return type indicate that a method could return an empty value. Also there are many people trying to use Optional as a type in their fields, this is a bad practice. Additionally, using Optional in a serializable class will result in a NotSerializableException.

Now let us conclude our thoughts on Optional class.

Optional class a concluding thought

In this article initially we have seen about NullPointerException in java. We then discovered about Optional classes and how they help to handle it. We learned how to create Optional objects using three ways. Then we learned about Optional class methods. Finally we discussed about the use case of Optional class.

Optional must be used to replace explicit null checks.

Use Optional as return type of method which may return null values.

Never use Optional as field value.

Optional allows us to chain the different methods easily.

Using Optional as a method parameter is a bad idea.

Thank you for reading this article, If you are preparing for java interviews I have a free course for you on Udemy please click here to enroll ->

https://www.udemy.com/course/400-java-interview-questions-and-answers/?couponCode=FREE100

Free coupon code: FREE100

--

--

Dsforgood

We are a bunch of data science enthusiasts simplifying concepts and ideas in technology for common readers. We believe in using data science for good!