‘this’ Keyword in Java

Ravi Chandola
Javarevisited
Published in
3 min readNov 25, 2022

Let's suppose we have a program which is having the same name as the variable in local and class-level variable scope.

class Ambiguity {
public static void main(String[] args) {
Opinion op = new Opinion();
op.print();
}
}

class Opinion{
int opt = 10;
public void print(){
String opt = "Make an opinion";
System.out.println(opt);
}
}

So when you gonna run this particular code, you will find that the output is : Make an opinion.

Output of the program

In order to access the class level variable we used ‘this’ in java. ‘this’ is a keyword that acts as a reference variable in java. It contains the address of the current object since it is also an instance reference variable which is the reason it cannot be addressed from the static context.

Now let us take a new example to understand ‘this’ keyword in depth

class Ambiguity{
public static void main(String[] args){
Medium med = new Medium(100,"Java Programming");
med.print();
Medium noob = new Medium(99, "OOPS Concept");
noob.print();

}
}

class Medium{
int followers;
String article;
Medium(int flollowers, String article){
this.followers = followers;
this.article = article;
}
public void print(){
System.out.println("Followers = "+followers+"\t"+"Article = "+article);
}
}

To better understand this we will take a screenshot of where line numbers are given.

So start with the main method as we can see in the screenshot, med is an object which passes 100 and “java Programming” as parameters to the two-args constructor in line 14 and sets passes the value for the same.

Now in line number 14, we have passed the following values as Medium(100, “Java Programming”) and now in the next line, we used this keyword to refer to the class level variable and set its value as 100.

this .follower -> null

but if you write this.follower=follower — it sets the class level instance variable as 100. The same is in the case of Article also.

From here we can say that we can use the same name as local and instance variables. When we access any variable directly then the following things happen :

  1. Checks whether that variable is declared in the local scope.
  2. If found in the local scope, that variable will be used.
  3. If not found in the local scope then, checks whether the variable is declared in the class scope.
  4. If it is found, the class-level variable will be used

When you have the same name for the local and class-level variables then,

  1. Refer to the local variable directly
  2. Refer to the class level variable using the ‘this’ keyword.

Note: Call to ‘this’ must be the first statement in the constructor.

--

--

Ravi Chandola
Javarevisited

As a technology enthusiast, I have a passion for learning and sharing my knowledge with others. https://www.linkedin.com/in/ravi-chandola-304522133