Java this keyword Purpose and Meaning Example

Java this keyword Purpose and Meaning Example

Before explaining Java this keyword, first let us see the problem then we will see a solution.

Sometimes in coding of any language including Java, local variable may clash with instance (global) variable. That is, both local variable and instance variable are same. If same, an unexpected result occur.

Observe the following simple code without using Java this keyword

Java this keyword

Now guess the output of marks of std1. Most probably you say simply it is 80. But it prints 0. See the output screen. What happened? How 80 became 0. Let us see.

The method parameters are treated as local variables.

In the above code, the parameter marks is treated as local variable in display() method.

marks = marks;

In the above statement, both marks are treated as local variables. The first marks is not instance variable. The rule is, if local and global variables clash, local is preferred (or to say, takes the precedence). That is, in the above statement, local variable is assigned to itself. That is, instance variable marks is not given value by std1 object. Then, the default will be 0. For this reason, the output is 0 and not 80.

Note: If instance variable is marks1 and the parameter is marks2, then the statement marks1 = marks2, never gives trouble and works fine.

Then, how to overcome this problem when clashing of variables exist?

The magic keyword is "Java this". Let us modify very slightly the above code to get 80 and not 0.

Java this keyword

In this.marks statement, this refers the current object of std1. What is current object? We are calling display() method with std1 as std1.display(). Then, this becomes std1 and std1 is known as current object. That is, the current object is that one with which the method is called. Internally, the statement becomes, std1.marks = marks. marks in std1.marks is instance variable. Now the local marks 80 value is assigned to instance variable marks. For this reason output came correctly.

Finally to say, this keyword refers the current object or to say, this is a pointer to the current object or to say, this refers always an object always (but not variable, method of constructor).

Note: this and this() are very different. this refers an object and this() refers a constructor. Similarly, super and super() are very different.

Precautions of usage of this keyword

  1. Should not be used with static variables
  2. Should not be used in static methods
  3. Should not be used with local variable (should be used with instance variables only)

Another usage of this keyword


The above statement, we used in event handling of Button (refer: Java AWT Button – Learning GUI – 8 Steps) to register or link the button with the ActionListener interface. Here, the parameter this refers an object of ActionListener.

Leave a Reply

Your email address will not be published. Required fields are marked *