java.lang.NullPointerException
Solution 1
You get a NullPointerException
when you try to call a method using a variable that is null
. Simple example:
String s = null;
int len = s.length(); // NullPointerException because s is null
So you should check if the variable is null
before calling any method on it, for example:
int len;
if (s == null) {
len = 0;
}
else {
len = s.length(); // Safe, s is never null when you get here
}
Note that a NullPointerException
is usually easy to solve. Carefully look at the stack trace of the exception; it tells you exactly in which line of your code the exception happens. Check what could be null
in that line of code, and check if you're calling a method on something that might be null
. Add a check (or prevent that the relevant thing can ever be null
in another way).
Solution 2
Simply do a proper check for the value being null
. A conditional such as
if (value == null)
will never raise a NullRefePointerException. It's only if you try accessing whatever a null
reference points to that you get the exception. So calling methods or accessing other instance members of the object is out of the question.
Solution 3
Use an if to check for the variable not being null and then use an else code block for when it is null.
if (variable != null)
{
// Code when object is not null
}
else
{
// Code when object is null
}
The null pointer is only thrown when you try and use the null value.
For example,
variable.method();
But you should always avoid a situation where a null pointer could occur.
Solution 4
As stated by other posters, if you do not expect the s reference to be null here then fix the bug that causes the reference to be null in the first place. However, if it is valid that the reference could be null, you can also do the following using the ternary operator (Java 5 on)
int len = (s == null) ? 0 : s.length;
Note: the brackets are optional, but they make it a bit more readable in my opinion.
Comments
-
kawtousse almost 2 years
I do a condition with a value when it is null and when it is not null. The time where this value is null I got the
java.lang.NullPointerException
.How could I deal with this in order to dismiss this exception?
I need the condition when the value is null and when it is not.