If you have spent some time developing programs in Java, at some point you have definitely seen the following exception:

java.lang.NullPointerException

Some major production issues arise due to NullPointerException. In this article, we’ll go over some ways to handle NullPointerException in Java.

Simple Null Check

Consider the following piece of code:

public static void main(String args[]) {
    String input1 = null;
    simpleNullCheck(input1);
}

private static void simpleNullCheck(String str1) {
    System.out.println(str1.length());
}

If you run this code as is, you will get the following exception:

Exception in thread "main" java.lang.NullPointerException

The reason you are getting this error is because we are trying to perform the length()operation on str1 which is null.

An easy fix for this is to add a null check on str1as shown below:

private static void simpleNullCheck(String str1) {
    if (str1 != null) {
        System.out.println(str1.length());
    }
}

This will ensure that, when str1isnull, you do not run the length()function on it.

But you may have the following question.

What if str1 is an important variable?

In that case you can try something like this:

 private static void simpleNullCheck(String str1) {
    if (str1 != null) {
        System.out.println(str1.length());
    } else {
        // Perform an alternate action when str1 is null
        // Print a message saying that this particular field is null and hence the program has to stop and cannot continue further.
    }
}

The idea is that, when you expect a value to be null, its better to put a null check on that variable. And if the value does turn out to be null, take an alternative action.

This is applicable not only to strings, but to any other object in Java.

#java #developer

How to Handle NullPointerException in Java
1.75 GEEK