nkukhar
nkukhar

Reputation: 2045

Is this in any way useful if (this != null)?

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?

Upvotes: 2

Views: 1157

Answers (5)

dimme
dimme

Reputation: 4424

The programmer was looking for a fancier way to write:

if (true) {

}

Upvotes: 1

Toph
Toph

Reputation: 2699

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!

Upvotes: 0

luizbag
luizbag

Reputation: 152

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.

Upvotes: 0

jjnguy
jjnguy

Reputation: 138972

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.

Upvotes: 2

Jesper
Jesper

Reputation: 206996

this can never be null in Java so this kind of code is never useful.

Upvotes: 16

Related Questions