Can "this" ever be null in Java? Can "this" ever be null in Java? java java

Can "this" ever be null in Java?


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 :


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


No never, the keyword 'this' itself represents the current alive instance (object) of that class within the scope of that class, with which you can access all its fields and members (including constructors) and the visible ones of its parent class.

And, more interestingly, try setting it:

this = null;

Think about it? How can it be possible, won't it be like cutting the branch you are sitting on. Since keyword 'this' is available within the scope of the class thus as soon as you say this = null; anywhere within the class then you are basically asking JVM to free the memory assigned to that object in the middle of some operation which JVM just can't allow to happen as it needs to return back safely after finishing that operation.

Moreover, attempting this = null; will result in compiler error. Reason is pretty simple, a keyword in Java (or any language) can never be assigned a value i.e. a keyword can never be the left value of a assignment operation.

Other examples, you can't say:

true = new Boolean(true);true = false;