How to avoid NullPointerException in Java


We often get NullPointerException and we do not understand how to resolve this exception.


Lets have a look at how the Exception occurs in certain scenarios and how we can fix them

Case 1: statement with equalsIgnoreCase/equals

First let's create an example function:

private Boolean isFinished(String status) {
    if (status.equalsIgnoreCase("Finish")) {
        return Boolean.True;
    } else {
        return Boolean.False;
    }
}

The above method should work in all cases, right? No! it'll throw NullPointerException if the value of status param is null

Why is this causing NullPointer?

Let's try to debug the case. 
When null is passed as a value for status param, the if condition becomes
if (null.equalsIgnoreCase("Finish"))
Here null doesn't have any function called equalsIgnoreCase and hence it is throwing NullPointerException (NPE)

To fix this:

We just need to swap the conditions of equalsIgnoreCase
Like below:
if ("Finish".equalsIgnoreCase(status))
So, our function becomes:

private Boolean isFinished(String status) {
  if ("Finish".equalsIgnoreCase(status)) {
      return Boolean.True;
  } else {
    return Boolean.False;
  }
}

Similarly, 

  • if we have object.equals("literal"then we should replace it with "literal".equals(object)
  • if we have object.equals(Enum.enumElement) then we should replace it with Enum.enumElement.equals(object)

In general, expose equals and equalsIgnoreCase method of the object that you are sure that it doesn't has null value.


Case 2: Empty Collection

What is Empty Collection?

Empty Collection is collection which has no elements/zero elements.

Some developers return null value for Collection which has no elements but this is bad practice, instead you should return Collections.EMPTY_LISTCollections.EMPTY_SET and Collections.EMPTY_MAP.

Code that cause NPE:

public static List getEmployees() {
  List list = null;
  return list;
}

Fixed code:

public static List getEmployees() {
  List list = Collections.EMPTY_LIST;
  return list;
}


Case 3: Use some Methods


Using some methods to assure that null value not exist like contains()indexOf()isEmpty()containsKey()containsValue() and hasNext().

Example:

String hello = "Hello World";

List list = Collections.Empty_LIST;
boolean exist = list.contains(hello);
int index = list.indexOf(hello);
boolean isEmpty = list.isEmpty();

Map map = Collections.EMPTY_MAP;
exist = map.conatinsKey(hello);
exist = map.containsValue(hello);
isEmpty = map.isEmpty();

Iterator iterator;
exist = iterator.hasNext();


Previous Post Next Post