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

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!”);

}

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Next Chapter

What is Cloud?

Google Data Center

Scraping Cost of Living Data From the Web Into a MySQL Database Using Python

How to import CSV/XSLX file with active admin?

How Serverless Cloud Works (Part 2)

Flutter installation and set up in a few steps (Windows)  —  For newbies

Integration of Git, GitHub, Jenkins and Kubernetes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sdet & Updates

Sdet & Updates

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

More from Medium

Java Appium Automation Framework with TestNG + maven Part 1

Container less Application with spring Boot

Builder Design Pattern

STRING IMMUTABILITY IN JAVA