java.lang.NullPointerException

java.lang.NullPointerException is the most commonly encountered exceptions while execution of applications written in java.
All java programmers are haunted by this exception since it mostly arises due to incorrect handling of null references.

This post will cover topics such as what it is, what is its cause, how to handle and avoid it.

What is NullPointerException
As its name states, a java.lang.NullPointerException is raised when the application code tries to call a method on a null reference.
A null reference means an object variable which has not been initialized or which does not point to any memory location.
Example,

String emptyRef;
String lowerCase = emptyRef.toString();

In the above example, emptyRef is a string variable declared but not initialized which means it is null.
Calling toString method on this reference translates to null.toString() and will raise a NullPointerException.

NullPointerException is an unchecked exception.

Javadoc for NullPointerException states

Thrown when an application attempts to use null in a case where an object is required.

Cause
A NullPointerException hereby referred to a NPE is not only raised when calling a method on null reference but it may also arise when accessing a field of a null object.

Below are the situations where a NPE can occur.
1. Calling a method on null reference.
2. Accessing field(instance variable) of a null reference.
3. Trying to get the length of an array when it is null. Example, Integer[] arr = null; int l = arr.length;
4. Accessing array location when the array is null. Example, Integer[] arr = null; arr[1] = 10;

Avoid NullPointerException
There are a couple of ways in which a NPE can be prevented. They are detailed below.
1. When creating an object, initialize it always.
In other words, give a default value other than null to an object.

For String objects, initialize them with empty value, for arrays, initialize array elements with either 0 for integer arrays, empty string for String array etc., and for other types create empty objects.
Example,

String str1 = "";               // empty string literal
String str2 = new String("");   // empty string object
Integer value = 0;              // integer object initialized to 0
MyClass obj = new MyClass();    // custom object initialized to empty

In all the above cases, no object is initialized to null.

2. A common scenario where NullPointerException occurs frequently is comparison using equals() method. Example,

String s = null;
// will be NullPointerException
boolean e = s.equals("codippa");

Integer i = null;
// will be NullPointerException
e = i.equals(10);

In such cases, where an object is compared with some value with equals(), it is suggested to place the value before the object.
Thus, above code can be modified to avoid NullPointerException as below.

String s = null; 
// will be false
boolean e = "codippa".equals(s); 
Integer i = null;
// will be false 
e = 10.equals.(10);

3. When calling a method, accessing a field on an object always perform a null check. Example,

int getLength(String s) {
   if(s != null) {
      return s.length();
   }
   return 0;
}

Many times, you call a method on a object which is supplied/created by an external library or class.
It might happen that the external library/class was not able to create the object properly due to some error or missing values and returned a null object.
Before calling any method on this object, a null check should be performed.
Example,

void readInput() {
   Scanner scanner = new Scanner(System.in);
   // check for null before calling method
   if(scanner != null) {
      scanner.readLine();
   }
}

4. Using Java 8 Optional
java.util.Optional introduced in java 8 is a container around an object.
To get the object contained in optional use its get() method. It provides methods such as isEmpty() to check if the underlying object is null, isPresent() to check if the object is present.
These methods when used as a check before calling get() may avoid NullPointerException.

Further, its orElse() method allows to return another object if the underlying object is null. An empty object may be returned from orElse() to prevent NullPointerException.

Finally, methods that return an object should return an Optional and calling methods should get the actual object after checking with ifPresent() or isEmpty(). Example,

public Optional<Employee> getById(int id) {
   // fetch object from database
   Employee emp = connection.getFromDb(id);
   // create optional
   return Optional.of(emp);
}

Calling method will be

public Employee getEmployee(int id) {
   Optional<Employee> eOp = getById(id);
   if(!eOp.isEmpty()) {
     return eOp.get()
   }
   return new Employee();
}

This will avoid NullPointerException guaranteed.


Catch NullPointerException

If even after above prevention steps, you still want that NullPointerException should not be seen at all, then you can also catch this exception using a trycatch block.
First identify the place where a NPE can arise, surround that code with trycatch block as shown below.

void readInput() {
   try {
      Scanner scanner = new Scanner(System.in);
      // check for null before calling method
      scanner.readLine();
   } catch(NullPointerException e) {
      e.printStackTrace(); 
   }   
}

That’s it on java.lang.NullPointerException. Hope it was useful.

Leave a Reply