The java.lang.NullPointerException
is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null.
Since the NullPointerException
is a runtime exception, it doesn't need to be caught and handled explicitly in application code.
Why NullPointerException Occurs in Java
The NullPointerException
occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
Some of the most common scenarios for a NullPointerException
are:
- Calling methods on a null object
- Accessing a null object’s properties
- Accessing an index element (like in an array) of a null object
- Passing null parameters to a method
- Incorrect configuration for dependency injection frameworks like Spring
- Using
synchronized
on a null object - Throwing null from a method that throws an exception
NullPointerException Example
Here is an example of a NullPointerException
thrown when the length()
method of a null String
object is called:
public class NullPointerExceptionExample {
private static void printLength(String str) {
System.out.println(str.length());
}
public static void main(String args[]) {
String myString = null;
printLength(myString);
}
}
In this example, the printLength()
method calls the length()
method of a String without performing a null check prior to calling the method. Since the value of the string passed from the main()
method is null, running the above code causes a NullPointerException
:
Exception in thread "main" java.lang.NullPointerException
at NullPointerExceptionExample.printLength(NullPointerExceptionExample.java:3)
at NullPointerExceptionExample.main(NullPointerExceptionExample.java:8)
How to Fix NullPointerException
To fix the NullPointerException
in the above example, the string should be checked for null or empty values before it is used any further:
import org.apache.commons.lang3.StringUtils;
public class NullPointerExceptionExample {
private static void printLength(String str) {
if (StringUtils.isNotEmpty(str)) {
System.out.println(str.length());
} else {
System.out.println("Empty string");
}
}
public static void main(String args[]) {
String myString = null;
printLength(myString);
}
}
The code is updated with a check in the printLength()
method that makes sure the string is not empty using the apache commons StringUtils.isNotEmpty()
method. Only if the string is not empty the length()
method of the string is called, else it prints the message Empty string
to console.
How to Avoid NullPointerException
The NullPointerException
can be avoided using checks and preventive techniques like the following:
- Making sure an object is initialized properly by adding a null check before referencing its methods or properties.
- Using Apache Commons
StringUtils
for String operations e.g. usingStringUtils.isNotEmpty()
for verifying if a string is empty before using it further. - Using primitives rather than objects where possible, since they cannot have null references e.g. using
int
instead ofInteger
andboolean
instead ofBoolean
.
Track, Analyze and Manage Java Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today!