Skip to content

Make Selenium Easy

And Keep It That Way

  • Home
  • Share
  • Toggle search form

Handle Horror Of NullPointerException Using Optional Class

Posted on 02/19/2025 By admin

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.

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());
        }
}
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 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.

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.

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

Uncategorized

Post navigation

Previous Post: Handling web table in selenium
Next Post: Implementation of Explicit Wait as FluentWait and WebDriverWait in Selenium WebDriver

Related Posts

What will happen if we pass NULL as argument in sendKeys() method Of Selenium WebDriver Uncategorized
How To Sort List In Ascending & Descending Order Using Java Stream API? Uncategorized
May 20, 2019 – Make Selenium Easy Uncategorized
BasicNavigationforGet – Make Selenium Easy Uncategorized
July 29, 2017 – Make Selenium Easy Uncategorized
TestNG Tutorials 44: Constructor with @Parameter Annotation | Make Selenium Easy Uncategorized

Recent Posts

  • Getting Started with Selenium 4: What Is New and How to Upgrade from Selenium 3
  • Manual Testing
  • Baby Steps To Become Efficient Selenium-Java Automation Tester
  • Features of Selenium 4.0.0 Release – Java Binding
  • Part 1: Handling Drop-down Created Using SELECT Tag In Selenium

Recent Comments

No comments to show.

Archives

  • April 2026
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • April 2024
  • March 2024
  • February 2024
  • December 2023
  • October 2023
  • August 2023
  • November 2022
  • September 2022
  • August 2022
  • July 2022
  • May 2022
  • March 2022
  • October 2021
  • April 2021
  • March 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • August 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • May 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • January 2018

Categories

  • Getting Started
  • Uncategorized

Copyright © 2026 Make Selenium Easy.

Powered by PressBook Masonry Dark