This domain is available for sale. Contact info2crazzybasket@gmail.com

How to avoid NullPointerException in Java


  NullPointerException will be thrown when an application attempts to use null in a case where an object is required. As per the Java API Doc, these are the possible situations.

  • 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.

NullPointerException is a RuntimeException that can be thrown during the normal operation of the Java Virtual Machine (JVM).
It is an unchecked exception. Since JVM is directly throwing this exception, we don't need to declare it in a method signature or in a constructor's throws clause.

Consider the following example:

1. int a;
2. a = 5;
3. Integer b;
4. int c;
5. c = b
6. b = new Integer(5);

In this example variable a is the primitive type int, so when the code execution reaches at line# 1, a is having the default value 0.
At line# 2, we are assigning the value 5 to a. From this point onward, a is having the value 5 until it is being assigned with a new value. In general, premitive types will always have a non-null value.

Let's consider the variable b, It got the reference type Intger, unlike its primitive type int, this reference type has a default value null. At line# 3, we are not assigning any value, so b is pointing to null. At line# 5, we are assigning a value of 5 to b by instantiating an object type of Integer by using the operator new. Now b is pointing to a proper memory location and holds a proper value.

Let's consider the variable c. Even though it is defined as a primitive type, at line# 5, it is assigned with the Integer reference b, which is not yet initialized. So, further usage of c will definitely through NullPointerException.

NullPointerException occurs when you try to access an object or its properties, before it is being initialized.


Other possibilities

Let's see this scenario:

public void myMethod(Object obj) {
obj.doSomething();
}

In this scenario, since obj is not owned by myMethod(), we cannot guarantee that obj will be always non-null. obj.doSomething() will through NullPointerException when obj is null.

Let's see this scenario:

//Assuming that obj is non-null
public void myMethod(Object obj) {
obj2 = outRefObject.getSomethingElse(obj);
obj2.doSomethingElse();
}

Here even though, obj is non-null, there is no guarantee that outRefObject.getSomethingElse(obj) will return a non-null object since we are not owning getSomethingElse().
There is a big chance of NullPointerException when you call obj2.doSomethingElse();

How can I avoid NullPointerException?
(i) Check for null

First is first. If your code is not owning the object under doubt, always go for null check, before using it.

public void myMethod(Object obj) {
if(obj != null) {
  obj.doSomething();
 }
}

(ii) Use the utility method Objects.nonNull(Object obj)

From 1.8 onward, java offers the static method nonNull(Object obj), that will return false if obj is null.

import java.util.Objects;
public void myMethod(Object obj) {
if(Objects.nonNull(obj)) {
  obj.doSomething();
 }
}

(iii) Do null check for the inner object too.

If your interest is not at obj, but one of its property (innerObj) of Object type, then you should do the null check for that inner object too.

import java.util.Objects;
public void myMethod(Object obj) {
if(Objects.nonNull(obj) && Objects.nonNull(obj.innerObj)) {
  obj.innerObj.doSomething();
 }
}

(iv) Use the utility method Optional.ofNullable(Object obj)

From 1.8 onward, java offers the static method ofNullable(Object obj), that will return an empty Optional object if obj is null. If obj is non-null, then this method returns an Optional object with obj. You can check the presence of an actual object by using either isEmpty() or isPresent() on this Optional object. The actual object can be obtained by calling get() on this Optional object.

import java.util.Optional;
public void myMethod(Object obj) {
if(Optional.ofNullable(obj).isPresent()) {
  Optional.ofNullable(obj).get().doSomething();
 }
}

It is a good practice to inform the caller of your method by throwing a message back, that you haven't processed the request since the caller failed to send a valid object.

How can I handle NullPointerException?

Yes, it is practically possible to handle NullPointerException like any other exceptions by the try...catch block.
But you should avoid handling NullPointerException or any RuntimeException why because all of them are unchecked exceptions.
NullPointerException is a clue to the developer to handle some possible defects in the code.

Conclusion

  • We have learnt what is NullPointerException.
  • When NullPointerException occurs.
  • How can we avoid NullPointerException.
  • Some good java coding practices.

Difference between ArrayList and LinkedList in Java

ArrayList and LinkedList are the two general-purpose List implementations. Both have its performance benefits based on the situation where it is being used. Read More

Difference between replace() and replaceAll() in Java

replace() will replaces all occurrences of oldChar in the string that invokes the method with newChar. Then why we need replaceAll()? Read More

How to compare strings in java

Strings in java can be compared either by using the operator == or by using the method equals(). intern() can generate a canonical representation of the string object. Read More