What is a NullPointerException? How do I fix it?
Question:
What are Null Pointer Exceptions (java.lang.NullPointerException)? How do I determine the cause? I want to stop the exception from causing the program to terminate prematurely.
Answer:
NullPointerException
occurs when you use a reference that points to no location in memory (null) and treat it as though it was referencing an object.
Calling a 1. method on a null reference or 2.trying to access a field of a null reference will trigger it.
There are also other ways are listed on the NullPointerException
javadoc page.
An example code is:
public class Example {
public static void main(String[] args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main
, the setting the Object
reference obj
equal to null
. This means there is a reference, but it is not pointing to anobject. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException
because there is no code to execute in the location that the reference is pointing.