What are Null Pointer Exceptions (java.lang.NullPointerException
) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
What are Null Pointer Exceptions (java.lang.NullPointerException
) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
It is also the case that if you attempt to use a null reference with
synchronized
, that will also throw this exception, per the JLS:How do I fix it?
So you have a
NullPointerException
. How do you fix it? Let's take a simple example which throws aNullPointerException
:Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Here, we see that the exception is thrown on line 13 (in the
printString
method). Look at the line and check which values are null by adding logging statements or using a debugger. We find out thats
is null, and calling thelength
method on it throws the exception. We can see that the program stops throwing the exception whens.length()
is removed from the method.Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that
s
is passed in withprintString(name)
in theprint()
method, andthis.name
is null.Trace where these values should be set
Where is
this.name
set? In thesetName(String)
method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.This is enough to give us a solution: add a call to
printer.setName()
before callingprinter.print()
.Other fixes
The variable can have a default value (and
setName
can prevent it being set to null):Either the
print
orprintString
method can check for null, for example:Or you can design the class so that
name
always has a non-null value:See also:
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using
this
references. Take this example:And on another place in your code:
This an important thing to know - when there are no more references to an object (in the example above when
reference
andotherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
The below code gives you a null pointer exception.
Because you are using
Obj_Student
, but you forgot to initialize it like in the correct code shown below:It's like you are trying to access an object which is
null
. Consider below example:At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw
NullPointerException
which makes sense.See this below example as well:
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid
NullPointerException
at all.See also: A good list of best practices
I would add, very important, make a good use of the
final
modifier. Using the "final" modifier whenever applicable in JavaSummary:
final
modifier to enforce good initialization.@NotNull
and@Nullable
if("knownObject".equals(unknownObject)
valueOf()
over toString().StringUtils
methodsStringUtils.isEmpty(null)
.In Java, everything is in the form of a class.
If you want to use any object then you have two phases:
Example:
Object a;
a=new Object();
Same for the array concept
Item i[]=new Item[5];
i[0]=new Item();
If you are not giving the initialization section then the
NullpointerException
arise.