How To Waive NPE, The NullPointerException in Your Code Flow?

Development & UX Researches
2 min readNov 3, 2020

--

NullPointerException

Do you get NPE aka NullPointerExceptions in your code very often?

Yeah, I know. It is a headache when it ruins your entire code. In java, either we compare values, look into the value through a loop, or retrieve from a collection value such as from a List, Set, or Map.

Do not forget that we avoid at all costs while using the “null” value in java. However, in some cases either;

-you are using a null initializer,

-the loop of an array points to a nonexistent index,

-the database returns a null value,

-the dependant methods did not work properly to return the value,

-the automation responded too late or early when brings the value, etc.

So how do we prevent this NPE error?

We can start from the beginning; How do we compare literals?

The below code will throw NPE

String str = null;if (str.equals(“abc123”)) { // NPE will be thrown at this line!System.out.println(“The values are equal!”);}else{System.out.println(“The values are NOT equal!”);}

What if we refer to the object but not the literal, it works fine?

String str = null;if (“abc123”.equals(str)) { // NO NPE will be seenSystem.out.println(“The values are equal!”);}else{System.out.println(“The values are NOT equal!”);}

How about if we guarantee not to stop the execution of automation framework, automation, or any part of your method execution because of the NPE error?

Good news, one more option we have java.util.Objects.

String str1 = null;String str2 = null;// NO NPE surely your code will not stop
if (Objects.equals(str1, str2)) {
System.out.println(“The values are equal!”);}else{System.out.println(“The values are NOT equal!”);

}

--

--

Development & UX Researches

A self-learner in the programming and UX industry. Keep yourself updated in this journey together ;)