Understanding NullPointerException And How To Avoid It In Java/Selenium

Hello Folks,

Very common question asked by people:

“I am getting NullPointerException in automation script. I am correctly using selenium concepts but unable to resolve it.”

So, in this post, we will see what is reason behind above exception and how to solve it.

What is NullPointerException?

When we declare a reference variable, internally a pointer is created to reference variable.

For example:

Suppose Demo is a class and we create an object of class Demo as below:

Demo d= new Demo();

See the below image:

Now consider below lines of code:

Demo d1;

Above, I just declared a reference variable/object of Class Demo. I am not initialing it. When a reference variable is not initialized, it points to NULL. It means reference variable is pointing to nothing.

And when we want to perform any action on such reference variable, we get  NullPointerException. 

We will see an example below:

Output:

We perfectly declared and initialized np1 and called print method on it. It printed output successfully. And we just declared np2 and did not initialized it. So np2 is pointing to null. When we call print method on it, we got NullPointerException.

As per JAVADOC:

NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

I can list out some more reasons of NullPointerException from here:

1) Invoking methods on an object which is not initialized 2) Parameters passed in a method are null 3) Calling toString() method on object which is null 4) Comparing object properties in if block without checking null equality 5) Incorrect configuration for frameworks like spring which works on dependency injection 6) Using synchronized on an object which is null

7) Chained statements i.e. multiple method calls in a single statement