Why do NullPointerExceptions happen?
A NullPointerException is caused by an attempt to dereference a
pointer that doesn't point to anything; the pointer is null. Here are
a couple of common scenarios where NullPointerExceptions can be found:
String myString = null;
System.out.println(myString.length());
Here a variable, myString, is declared and initialized to null on line #1. When line #2
attempts to deference the variable myString in order to print the
string's length, a NullPointerException is thrown because myString
doesn't point to anything.
System.out.println(aMethodThatReturnsNull().toString());
This second example is a little trickier. No variable was declared, but
there is still a pointer: the return value of the method
aMethodThatReturnsNull(). That fictitious (and seemingly useless)
method will always return null. As we saw in the first example,
attempting to dereference a null pointer and call a method on the
referenced object (which is null) results in a NullPointerException.
How do you track down a NullPointerException?
To find the source of a NullPointerException, start with the stack
trace. In your Java console or log file, you'll see something like
this:
Exception in thread "main" java.lang.NullPointerException
at com.foo.example.NullPointerExample.main(NullPointerExample.java:21)
The stack trace tells you what happened (NullPointerException) and
where (line 21 of NullPointerExample.java). Look at that line and see
if you can recognize one of the two patterns given above. Ask yourself
these questions:
- Are you calling a method on a variable that might be null?
- Are you calling a method on the return value of another method, where the first method might return null?
- Are you absolutely sure the answer to the first two questions was "no?"
NullPointerExceptions can happen for
other reasons, but these two are by far the most common.
http://publicint.blogspot.com/2009/04/nullpointerexception.html