Java has a lot of keywords like static keyword in java, final keyword in java, this keyword in java, super keyword in java, etc. In this post, we will discuss the “this” keyword in java and the use of “this” keyword in java. this keyword is a reference variable that refers to the current object of the class. Many people know it as this operator in java. So, let’s see what this keyword is, how it works, and this keyword in java with example.
What is this keyword in java?
As we know java is an object-oriented language, A application can have any number of objects. The “this” keyword in Java is used to refer to the current object/instance or constructor of the class. It means we can access any class variable and method of the class by use of this keyword. The objective of this keyword is to eliminate confusion when we have the same variable name for instance variables and local variables. There may be a situation when the class variables (instance variables) and parameters of the method have the same name.
1. this keyword in java refers to the current class variable
2. this keyword in java refers to the current class method
3. Used in constructor chaining
4. this as an argument in the method call
5. this as an argument in the constructor call
6. Using ‘this’ keyword to return the current class instance
1. The “this” keyword in java refers to the current class variable
In Java, we can’t create two instance variables or two local variables with the same name. But we can create one instance variable and one local variable or method parameter with the same name. Now the question arises if we have an instance variable and local variable with the same name then which one will be used and how compiler recognized that? So, to resolve this ambiguity this keyword comes into the role. It is also known as variable hiding.
The “this” keyword in java is used to differentiate the instance variable and local variable or parameters of the method.
Firstly, we will do the code without this keyword and try to understand the problem. After that, we can understand the use or need of this keyword in java.
In this example, we have a class Student having some instance variables and one parameterized constructor to initialize the values of variables. In the parameterized constructor, we are taking the parameter name the same as with the same instance variables. The compiler can’t make any difference in instance variables and parameters because both names are the same. Let’s see what the output will be :
public class Student { String name; int rollNo; String className; Student(String name, int rollNo, String className) { name = name; rollNo = rollNo; className = className; } public void printData() { System.out.println("Name = "+name); System.out.println("Rollno = "+ rollNo); System.out.println("Class Name = "+ className); } public static void main(String args[]) { Student student = new Student("Ram",5, "MCA"); student.printData(); } }
Output:
Name = null
Rollno = 0
Class Name = null
Explanation of the above example
In the above example, The compiler is not able to make any difference between the instance variable and the parameters of the constructor. It is assigning the value of parameters to local variables rather than the instance variable. Now we will do the same thing with this keyword.
public class Student { String name; int rollNo; String className; Student(String name, int rollNo, String className) { this.name= name; this.rollNo = rollNo; this.className = className; } public void printData() { System.out.println("Name = "+name); System.out.println("Rollno = "+ rollNo); System.out.println("Class Name = "+ className); } public static void main(String args[]) { Student student = new Student("Ram",5, "MCA"); student.printData(); } }
Output:
Name = Ram
Rollno = 5
Class Name = MCA
By using this keyword compiler can differentiate the parameters and instance variables.
Let’s take another example of an instance variable and a local variable. In this example, we are creating the instance variable and local variables with the same name. So when we use them and perform some operation then the compiler can’t differentiate them. Let’s see what the output will be:
public class ExampleOfThisKeyword { int a = 10 ; public static void main(String arg[]) { ExampleOfThisKeyword obj = new ExampleOfThisKeyword(); obj.showData(); } public void showData() { int a = 5; System.out.println("Value of a = " + a); } }
Output: Value of a = 5
In the above example, you have seen the compiler always gives preference to local variables. To use the instance variable, we must use this keyword. Let’s see how we can use the instance variable:
public class ExampleOfThisKeyword { int a = 10 ; public static void main(String arg[]) { ExampleOfThisKeyword obj = new ExampleOfThisKeyword(); obj.showData(); } public void showData() { int a = 5; System.out.println("Value of a = " + this.a); } }
Output: Value of a = 10
As you know we can’t access the non-static instance variable without the object. So, whenever we want to access them, we don’t need to create an object of the class, we can use this keyword as you have seen in the above example.
2. The “this” keyword in java refers to the current class method
this keyword in java refers to the current object of the class. So if we want to invoke the method within the class you can use this keyword. By use of this keyword, you don’t need to create the object of the class.
public class Student { String name; int rollNo; String className; Student(String name, int rollNo, String className) { this.name = name; this.rollNo = rollNo; this.className = className; } public void calulatedData() { System.out.println("This method is called by using of this keyword"); } public void printData() { System.out.println("Name = "+ name); System.out.println("Rollno = "+ rollNo); System.out.println("Class Name = "+ className); this.calulatedData(); } public static void main(String args[]) { Student student = new Student("Ram",5, "MCA"); student.printData(); } }
Output:
Name = Ram
Rollno = 5
Class Name = MCA
This method is called by using this keyword
NOTE: If you don’t use this keyword, the compiler automatically adds this keyword while invoking the method.
An important point to refer current class variable
We can’t use this keyword in a static block or static method. Because the static block or static method always binds with the class rather than objects. You have discussed it in a separate post you can read it from here (Restriction on this keyword) If you try to use this keyword in a static block or static method it shows a compilation error.
public class ExampleOfThisKeyword { int a = 10 ; public static void setData(int a) { this.a = a; } public void showData() { System.out.println("Value of a = " + this.a); } public static void main(String arg[]) { ExampleOfThisKeyword obj = new ExampleOfThisKeyword(); setData(5); obj.showData(); } }
Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Cannot use this in a static context at ExampleOfThisKeyword.setData(ExampleOfThisKeyword.java:7)
at ExampleOfThisKeyword.main(ExampleOfThisKeyword.java:16)
3. Used in constructor chaining
Please read the constructor chaining first after that you can understand it better. By use of this keyword, we can invoke the constructors.
Note: this keyword should be in the first line whenever you want to call a constructor. It is used in the chaining of a constructor. You can read it here.
public class Student { String name; int rollNo; String className; Student(String name) { System.out.println("This constructor is called by using of this keyword"); System.out.println("The name of Student = " + name); } Student(String name, int rollNo, String className) { this(name); this.name = name; this.rollNo = rollNo; this.className = className; } public void printData() { System.out.println("Name = "+ name); System.out.println("Rollno = "+ rollNo); System.out.println("Class Name = "+ className); } public static void main(String args[]) { Student student = new Student("Ram",5, "MCA"); student.printData(); } }
Output:
This constructor is called by using of this keyword
The name of Student = Ram
Name = Ram
Rollno = 5
Class Name = MCA
4. this is an argument in the method call
this keyword refers to the current object of the class. If you want to perform some operation by use of an object you can use this keyword. In the below example, we want to print the details of each object so we can simply pass this keyword in the method.
public class Student { String name; int rollNo; String className; Student(String name, int rollNo, String className) { this.name = name; this.rollNo = rollNo; this.className = className; } public void printData() { System.out.println("Name = "+ name); System.out.println("Rollno = "+ rollNo); System.out.println("Class Name = "+ className); printInfo(this); } public void printInfo(Student student) { System.out.println("New studnent name: "+ student.name + " and Rollno :" + student.rollNo); } public static void main(String args[]) { Student student = new Student("Ram",5, "MCA"); student.printData(); } }
Output:
Name = Ram
Rollno = 5
Class Name = MCA
New studnent name: Ram and Rollno :5
5. this is an argument in the constructor call
As like method call we can pass this as an argument in the constructor call. We can pass this keyword in the constructor also it is very similar to the method.
class Data { Record obj; Data(Record obj) { this.obj=obj; } void display() { System.out.println(obj.data);//using data member of Record class } } class Record { int data=10; Record() { Data b=new Data(this); b.display(); } public static void main(String args[]) { Record a=new Record(); } }
Output: 10
6. Using the ‘this’ keyword to return the current class instance
We can use the “this” keyword, where we want to return the current object.
In the below example, we are creating a getInstance() method that returns the object of the class.
public class Student { String name; int rollNo; String className; Student(String name, int rollNo, String className) { this.name = name; this.rollNo = rollNo; this.className = className; } public void printData() { System.out.println("Name = "+ name); System.out.println("Rollno = "+ rollNo); System.out.println("Class Name = "+ className); } public Student getInstance() { return this; } public static void main(String args[]) { Student student = new Student("Ram",5, "MCA"); student.getInstance().printData(); } }
Output:
Name = Ram
Rollno = 5
Class Name = MCA
This code is very challenging and helpful for me
And everyone also try it…
Thankyou Sangita
Thanks you very much