java.lang.NullPointerException

Previous
Next

In this tutorial, we will see the most frequent java exception i.e. NullPointerException. It is one of the Runtime Exception.

Raise your hand if you ever got NullPointerException while working on java code. I am sure that this is the exception you might have encountered most frequently. You might also agree that NullPointerException is pain for most of java developers(novice or expert), but there is not much we can do about them, because this is the price we need to pay for convenient or unavoidable null references.

NullPointerException

Reasons for NullPointerException

Reasons for NullPointerException as defined by Java docs.

  • Invoking 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.
  • When you add null to Collections which do not allow nulls such as ConcurrentHashMap
  • Trying to synchronize using null object.

Let’s understand each of these in detail. I am creating a Employee class which we are going to use in our examples.

1. Invoking the instance method of a null object

This is most obvious one.

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)

As you can see, e1 is null at line 7 and we are calling getMethod on it, thats why we are getting NullPointerException here.

2. Accessing or modifying the field of a null object.

It is very much similar to calling instance method on null.

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.NullFieldExampleMain.main(InvokingMethodOnNullMain.java:8)

As you can see, e1 is null at line 8 and we are accessing name field of e1, thats why we are getting NullPointerException here.

3. Taking the length of null as if it were an array.

When you try to get length of null array, you will get NullPointerException.

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.NullArrayLengthMain.main(InvokingMethodOnNullMain.java:9)

4. Accessing or modifying the slots of null as if it were an array.

When you try to access or modify null slot in array.Let’s understand with the help of example.

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:8)

5. Throwing null as if it were a Throwable value.

When you throw null as Throwable.

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)

6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1022)
at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1017)
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)

7. Trying to synchronize using null object.

When you synchronize on null object, you will get NullPointerException

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)

Detection of NullPointerException

It is easier to detect NullPointerException. Check exception trace, it will tell you class name, method name and line number.Go to that line number and check what can be the reason for NullPointerException.


Fix NullPointerException

Let’s take above scenrios and fix NullPointerException.

1. Null check

check null before calling method or field.

When you run above program, you won’t get NullPointerExcpetion.

2. Do null check as well before putting key or value in Collection which do not allow null


Best practices for avoiding NullPointerException

1. String comparison

This is most frequent reason for NullPointerExcpetion, let’s understand with the help of example.

As we did not set name of Employee e1, we will get NullPointerException here.
When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.StringComparisonMain.main(StringComparisonMain.java:8)

You can change logic as below.

This will avoid NullPointerException.
Please note that it may cause unexpected behavior due to null. If name cannot be null at all for Employee, then don’t use above method as it will ignore null names in this case.

2. Use Optional

Java 8 has introduced a new class called Optional.In general, we do not find any value in method, we return null from it and it becomes pain for caller to check for null to use it.
For example:

As you can see, if we did not find employee in employeeList, we are returning null from findEmployee method. The caller will get  employee object from findEmployee method and may call getName() method which will in turn raise NullPointerException.You can use Optional to avoid such situations.

There is no employee with name John

It gives indication to caller than returned value can be null.

3. Use ternary opertor

You can use ternary operation to check for null.

As you can see, we won’t get NullPointerException here.

4. Keep check on arguments of method

5. Use StringUtils from Apache Common

You can use StringUtils class to take care of lots of String null and empty String check. Sometimes you need to check if String is null or empty, you can use isEmpty method from StringUtils to take care of it.

That’s all about NullPointerException in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog