I got this piece of code from a commercial product. I believe that it will always throw the java.lang.NullPointerException exception when this.result is null. Am I right to say that?
private void closeCurrentResult() throws SQLException {
this.lastUpdateCount = -1;
if(this.result != null) {
this.result.close();
}
this.result = null;
}
if this.result is null, then
this.result = null
is equivalent to
null = null;
while causes the NPE.
After read through some of the replies, I think the thing becomes clear. I also did a test as the code shown below:
public class NullTest {
public static void main(String[] args) {
ABC a = new ABC(null);
a.test();
}
static class ABC {
Object result;
ABC(Object result) {
this.result = result;
}
void test() {
if (this.result != null) {
System.out.println("do something");
}
this.result = null;
}
}
}
And it works just fine.
resultis not being dereferenced (you're not calling a method onresult), no NPE will be thorwn. Also, assigning it a new value (whatever it is) will not cause the NPE even if the original reference was null.