tags:

views:

1349

answers:

9

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?

+36  A: 

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 :

Colin Hebert
Using it can, however, fail to compile. If it compiles then it's safe to use.
Mark Peters
Is it just nonsense to do such a check or is it actually prevented by the java language that such a thing can happen? I.e is the null pointer exception thrown before entering the method or only when a member is tried to be accessed? In comparable situations in other languages (in particular C++), this case is undefined behavior and the language will not actively prevent such a scenario.
Johannes Schaub - litb
I don't know deeply about Java, but in C++ the `this` of an instance method could be NULL. So I am not quite convinced this is a sufficient reason in Java.
KennyTM
@Mark Peters: What usages could fail to compile? Use in a static class is the only thing I can think of right now.
FrustratedWithFormsDesigner
@Johannes: `this` will only compile when it is used in the context of an instance. If somebody tries to call an instance method without giving an instance, it won't compile for *them*, or they'll get an NPE when trying to invoke it on an object. Runtime behaviour is basically irrelevant here unless you do some crazy bytecode manipulation.
Mark Peters
@Frustrated: In a static method or static initializer, yes. Or the RHS of a static assignment+declaration.
Mark Peters
the null pointer exception in something like `foo.bar()` would be thrown when `foo` is discovered to be `null`. it does happen before entering the method, but the real story is that there is no method to attempt to call.
Claudiu
@KennyTM: it is sufficient in Java. If you're using the `this` keyword and it compiles, it's not null when you observe it. But as others say that doesn't prevent an NPE when trying to invoke the method, e.g. But that's completely out of your control as a method and a null check within the method isn't going to change anything.
Mark Peters
@Kenny: Not without [undefined behavior](http://stackoverflow.com/q/1844005/54262), though if you know your implementation's details, you could use it.
Roger Pate
+21  A: 

It's like asking yourself "Am I alive?" this can never be null

Bragboy
_am_ I alive?! o god i don't know anymore
Claudiu
Cogito ergo sum
Martin Smith
Sum ergo this...
quixoto
You're making it sound like `this != null` was self-evident. It isn't - in C++, for example, `this` may well be `NULL`, for a non-virtual method.
nikie
@nikie In some sense, it's self-evident. Even in C++, any program where this happens has undefined behavior. It can also happen for virtual functions on GCC: http://ideone.com/W7RmU .
Johannes Schaub - litb
I do often wonder if I am in hell.
John Isaacks
@John: You are. Part of the torture is you can't confirm it.
Roger Pate
+2  A: 

No. To call a method of an instance of a class, the instance has to exist. The instance is implicitly passed as a parameter to the method, referenced by this. If this was null then there'd have been no instance to call a method of.

Claudiu
A: 

In static class methods, "this" isn't defined since "this" is associated with instances and not classes. I believe it would give a compiler error to attempt to use "this" keyword in static context.

burkestar
+3  A: 

If you compile with -target 1.3 or earlier, then an outer this may be null. Or at least it used to...

Tom Hawtin - tackline
I guess through reflection we can set the outer this to null. could be an April fool joke on someone when he got null pointer exception in referencing `Outer.this.member`
irreputable
A: 

Within the context of a static method (as others have already pointed out), including within an application Main method, the "this" keyword would likely have nothing appropriate to reference, and would return null.

Otherwise, assuming that your code is within an instance method of property of a class, and thus can only run in the context of an instantiated object, this always reference that object.

I believe this would apply to Java or C#. Not sure about others...

Thogek
there is no `this` inside a static method. It is the compiler that creates it for a non-static method. The first variable of a static method 'usually occupies' the same slot in the stack that, would be used for `this` in a non-static method.
Carlos Heuberger
The code won't compile so it cannot possibly execute and have a value, whether null or anything else.
EJP
Doh. The compiler would likely complain in the static-method case. Duh. Nevermind. :-/
Thogek
A: 

I don't know about in Java, but in C++ (although yes this test would be silly to do at the start of a function) later on it may make sense as it is possible that an object can delete itself halfway through its own code and then continue running that code. For example, the following compiles with no errors under gcc 3.4.4 but if run will crash with a NULL access error due to 'this' becoming a NULL pointer.

void foo::bar()
{
    delete this;
    this->some_function();
}
qwerty1793
Isn't it possible to call any non-virtual function with a NULL this-pointer?
Gabe
No, sorry. This answer is completely wrong..
Johannes Schaub - litb
C++ is not Java. Java is not C++. Is Java not C++. Is C++ Java not. Not is Java C++. Not is C++ Java. C++ not is Java. Java not C++ is. There. I've said it in as many different forms of grammar as I can think of this early in the morning. Maybe one of those forms will explain to you why answering a question about Java with C++-derived knowledge is a Bad Idea<tm>.
JUST MY correct OPINION
See [c++ checking for this == null](http://stackoverflow.com/q/1844005/54262)
Roger Pate
A: 

When you invoke a method on null reference, the NullPointerException will be thrown from Java VM. This is by specification so if your Java VM strictly complies to the specification, this would never be null.

tia
A: 

tl;dr, "this" can only be called from a non-static method and we all know that a non-static method is called from some sort of object which cannot be null.

Adam