How to deal with NullPointerException in Java

NullPointerException in Java

According to the detail mentioned in JavaDocs  below points covered for nullpointerexception in java:

Thrown when an application struggle 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.

It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS:

  • Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

How do I Deal with it?

So you have a NullPointerException in java. How do you deal with it? Let’s take a simple example which throws a NullPointerException:

Identify the null values

The first step is identifying just which values are creating the exception. For this, we wish to do some debugging. It’s critical to learn to read a stacktrace. This will show you where the exception was thrown:

Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method.

Trace where these values come from

Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(thatsjavainfoname) in the thatsjavainfo() method, and this.thatsjavainfoname is null.

Trace where these values should be set

Where is this.thatsjavainfoname set? In the setName(String) method. With some more debugging, we can see that this method isn’t called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn’t called after the print method.

This is enough to give us a solution: add a call to thatsjavainfo.setName() before calling thatsjavainfo.thatsjavainfo().

Other fixes

The variable can have a default value (and setName can prevent it being set to null):

Either the print or printString method can check for null, for example:

Or you can design the class so that name always has a non-null value:

Facebook