Handle Horror Of NullPointerException Using Optional Class

Introduction

Everyone knows the horror of NullPointerException. If we do not put checks on the null value then the execution of the program will be terminated abruptly and sometimes we require a lot of debugging to identify which variable is going null.

Did you know that I have started a YouTube channel as well and I need your support to make it successful. Please do watch content then comment, like, share, and obviously subscribe.

Program without null check

See the below code. I am not putting any null check on the global static variable and trying to get the length of a string “firstName”.

package optionalExamples;

public class HorrorOfNullPointerException {
	
	static String firstName;
	
	public static void main(String[] args) {
		// No check of null
		System.out.println(firstName.length());
	}
}
Output
Exception in thread "main" java.lang.NullPointerException
	at optionalExamples.HorrorOfNullPointerException.main(HorrorOfNullPointerException.java:9)

We can have a null check on the above variable to avoid NullPointerException.

package optionalExamples;

public class HorrorOfNullPointerException {

	static String firstName;

	public static void main(String[] args) {
		// with check of null
		if (firstName != null)
			System.out.println(firstName.length());
	}
}

In the above program, we will not encounter NullPointerException as we have a null check now.

In real-time we may have many variables which might be null and putting checks for all is not an easy task. We have another option to handle these effectively using the Optional class which was introduced in Java 8.

Optional Class

Optional is a final class that was introduced in Java 8. It is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

The last lines of the above paragraph will make more sense with examples that I will cover now.

There is a static method in the Optional class named ofNullable() that returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. In simple words, if the value is not null then return the value otherwise return empty.

package optionalExamples;

import java.util.Optional;

public class HandleNullPointerExceptionUsingOptional {

	static String firstName;

	public static void main(String[] args) {
		// ofNullable Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
		Optional fnOptional = Optional.ofNullable(firstName);
		// Check if value is present i.e. value is not null
		if (fnOptional.isPresent())
			System.out.println(fnOptional.get().length());
		else
			System.out.println("FirstName has no value.");

	}
}

Now you will get output as “FirstName has no value.“.

If we see the implementation of isNullable() method then you can find it check for null internally.

public static  Optional ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

In fact, I don’t find it useful as checking for null explicitly or using Optional class are the same and I feel there are extra lines of code involved in Optional class. But there are some methods which I really like and want to share here.

orElse(T other) Method

I really like this method of Optional class and use it extensively in coding. This method can be used to return other values in case of null. It is really helpful in providing default values to variables.

package optionalExamples;

import java.util.Optional;

public class OptionalOrElseExample {

	static String firstName;

	public static void main(String[] args) {
		// If firstname is not given use "Amod"
		firstName = Optional.ofNullable(firstName).orElse("Amod");
		System.out.println(firstName);
	}
}

We will get output as “Amod” as firstName is null.

There are many methods in Optional class and we will see some useful methods in upcoming posts.

Usage in Selenium

We can use this in Selenium scripts to handle data dependency. Suppose for registering a user we may require some details like name, address, etc. This data needs not be passed through data sources always. Our script should take data if provided or use some default or random data in case no data is passed. We can integrate Faker API of Java with it to generate proper random data for our tests.

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Leave a Reply

Your email address will not be published. Required fields are marked *