How to avoid NullPointerException in Java
Most of the developer’s idea is null checks makes the code less understandable and less reliable. Tony Hoare, who invented null references, calls them “a billion-dollar mistake”.
In object-oriented computer programming, a null object is an object with no referenced value. There are several places where null checking comes up,
- 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 they were an array.
- Throwing null as if it were a Throwable value.
The first thing you need to consider to avoid NullPointerException, is try to avoid use null values. So try to have fields and local variables with non-null default values.
When you are writing your code you have control over the code. If null is a valid response, you have to check for it.
public void method(Object object) {
if (object == null) {
// do something
}
}
Otherwise, avoid using nulls as a response. When methods that return collections or arrays, return empty collections or arrays instead of nulls.
Since java 7 you can use Objects methods,
Objects.isNull(object)
Objects.nonNull(object)
Objects.requireNonNull(object)
Objects.equals(object1, object2)
Since java 8 you can use Optional class ,
object.ifPresent(obj -> ...)
Advantages of Java 8 Optional is null checks are not required, no more NullPointerException at run-time and you can develop clean and neat APIs.
In special cases like Strings and Collections you can use apache commons utility methods,
public static boolean isEmpty(CharSequence cs) //apache CollectionUtils
public static boolean isEmpty(Collection coll) //apache StringUtils
public static boolean isEmpty(Map map) //apache MapUtils
An alternative solution is to never return null and instead use the Null Object pattern. The null reference to convey the absence of an object, you can use an object which implements the expected interface, but whose method body is empty, it does nothing. The advantage of this approach over a working default implementation is that a null object is very predictable and has no side effects.
public interface Animal {
void makeSound() ;
}
public class Dog implements Animal {
public void makeSound() {
System.out.println("woof!");
}
}
public class NullAnimal implements Animal {
public void makeSound() {
// body is empty, it does nothing
}
}