Avoid NullPointerException in Java

NullPointerException is popular exception in Java programming. Even those who experienced code for many years are also defective. I often troll my colleague in my company that: I see you are very good at code, never face with error, if have, only with NPE (stands for NullPointerException).

So, in this tutorial, I would like to share with you all some ways to avoid this exception. Of course, you usually have to exercise it, because we are human, we usually forget something. Me too 😀

Why do we usually face with this exception? That is because sometime, we cannot know the object which we are using, already initialized or not. If they were not initialized, this exception will happen!

I can list some cases that this exception will happen:

Compare two String objects

Let look at the code as below:

What is happen if the name variable in this method is null, when run our application, an exception will be thrown.

So in this case, how should we code? Below is a hint for you:

You can see because the string “David” is never null object, so when we tried to use it to compare with the name variable, NullPointer Exception will not happen.


Returns a null value when handling an empty collection

Consider the code as below:

If someone use this method in their application, they tried to read the collection, they will face with NullPointerException right away.

So, for an empty collection, we should return that empty collection. Empty collection will not a cause of a problem.

In Java, we have Collections object that helps us can return an empty collection without must memory. We have Collections.EMPTY_LIST for List object, Collections.EMPTY_SET for Set object and Collections.EMPTY_MAP for Map object.

So, with above example, I can re-write it as below:



Accessing an object may be null

In case, we are not sure when our object is null and we still want to use it in case it is not null. With this situation, we can use one in some ways as below:

  • The first way that is we will check the object can be null in some cases. If the object is not null, we will continue processing otherwise will stop processing. Example as below:

  • The second way, we can use try … catch in Java to catch this exception.

Since Java 8, we have other solution to avoid NullPointerException in Java by using Optional object.

 

Add Comment