Can "this" ever be null in Java?

Bryce Fischer picture Bryce Fischer · Sep 24, 2010 · Viewed 21.9k times · Source

Saw this line in a class method and my first reaction was to ridicule the developer that wrote it.. But then, I figured I should make sure I was right first.

public void dataViewActivated(DataViewEvent e) {
    if (this != null)
        // Do some work
}

Will that line ever evaluate to false?

Answer

Colin Hebert picture Colin Hebert · Sep 24, 2010

No it can't. If you're using this, then you're in the instance so this isn't null.

The JLS says :

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.

If you invoked a method from an object, then the object exists or you would have a NullPointerException before (or it's a static method but then, you can't use this in it).


Resources :