I am getting this error about "possible null pointer dereference of rellist in java" can you guy help me out
'for (int length2 = (array2 = relList).length, l = 0; l < length2; l)'
CodePudding user response:
error about "possible null pointer dereference of rellist in java"
That's not an error, that's a warning. Java itself doesn't do this; it's a so-called "linter" tool - a tool that checks code and tries to determine if it "looks bad". "looks bad" does not imply "will not run" nor does it imply "won't compile". It simply implies: This code may not do what you think it does, or will be hard to maintain. Hence, a warning. Not an error.
What the warning is trying to tell you is that you're effectively calling relList.length
, i.e. you're "dereferencing" the relList
variable, and the linter tool is telling you that relList
is either null
at this location or is likely to be null
in reachable code paths. For example, because you wrote if (relList == null)
earlier, and didn't exit the method or initialize relList
inside that if block, which indicates you certainly thought it could be null earlier on.
Here's an example of what a linter tool does:
void foo(String arg) {
if (arg == null) System.out.println("Please specify an argument");
if (arg.length == 0) System.out.println("Please don't specify an empty string");
}
This code compiles and runs perfectly fine, however, it's "stupid". If you pass null, this code will first print "Please specify an argument" and will then echo a NullPointerException stacktrace to the terminal. The odds that the author of this code intended that behaviour is near zero. The same linter tool you are using will flag arg.length
with that exact error ("possible null pointer dereference").
So what do you fix? We can't tell - you didn't include your code. The linter tool thinks it should be fairly obvious: Either deal with relList
being null
here, or alternatively scan your method because other code in your method apparently is written to deal with it being null
, so if you conclude relList
cannot possibly be null, remove that code then - it is useless.
CodePudding user response:
If a variable value is assigned as null, and we try to access it with any inbuilt method ( .length here), then null pointer dereference issue comes.
Put a check of not null and proceed.