A NullPointerException is an error that occurs when you try to access a null object. This can happen when you forget to initialize an object, or when you try to access an object that doesn’t exist.
To fix a NullPointerException, you need to find the line of code that is causing the error and either initialize the object, or change the code so that it doesn’t try to access the null object.
Null Pointer Exception, java.lang.NullPointerException
or NPE is a very common issue in Java. It’s raised when you try to access the property of the object that’s equal to null
The problem
So, NullPointerException is raised when you try to do something with a null
instead of the object.
A common scenario is a function that accepts an argument.
public void doSomethingUseful(SomeUsefulObject obj) {
obj.someUsefulMethod(); // you'll get an NPE if obj is null here
}
The function doSomethingUseful
accepts a single parameter of the type SomeUsefulObject
and then
calls its method someUsefulMethod
to presumably do something useful.
If obj
is evaluated to null
, you’ll see a NullPointerException
in logs.
java.lang.NullPointerException
is a RuntimeException
, so there’s no way to catch it during
compilation.
The solution
The fix is straightforward.
Find the place if your code where the issues occurs and make sure you’re not trying to access any
fields or methods of null
.
public void doSomethingUseful(SomeUsefulObject obj) {
if(obj != null) {
obj.someUsefulMethod(); // NPE is impossible as we just checked that obj is not null
}
}
As easy as it seems, it’s likely not the best solution for you.
You may want to go deeper to find out the reason why obj
evaluated to null
.
Ask yourself a question: “Is it possible for doSomethingUseful
to be useful if obj
is null?”
And if the answer is no, then a NullPointerException
is a great way to communicate to you
that something’s wrong with your logic or data.