I came across some tests that included code like this:
if (this != null) {
do something
}
Is this if clause of any use? Is there a purpose I don't get that makes this useful?
I came across some tests that included code like this:
if (this != null) {
do something
}
Is this if clause of any use? Is there a purpose I don't get that makes this useful?
this
can never be null
in Java so this kind of code is never useful.
In Java the this
keyword can only be used in a non-static method of a class.
Thus, if you are ever running code in the method, this
cannot ever be null
because you are guaranteed to have an instance of that object, otherwise the method would have never been able to be called.
You can't use "this" in a static environment that is the only place where "this" could be null.
You can call a static method or variable without an object, without an instance. "this" points to the current instance of the class. You can only use "this" if you have an object, so it will never be null.
I'm a pretty clueless programmer, so don't believe a word I say (and correct me if I'm wrong!), but it calls to mind cogito ergo sum -- I think, therefore I am. Descartes called it "the first and the most certain which presents itself to whoever conducts his thoughts in order." Similarly, that this != null
seems to be (in Java, anyway, from the sound of it) among the most trivial conclusions code can reach. Neat!