This Keyword In Java

There are a lot of keywords in Java, like static, final, this, super, etc. This post will discuss the keyword ‘this’, what it is, and how it works. This keyword is a reference variable that refers to the current object of the class. Some people know it as the ‘this’ operator in Java. Let’s take a look at what this keyword is with some examples.

This keyword in Java refers to the class’s current object/instance or constructor. It means we can access any class variable and method of the class by using 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 class variables (instance variables) and method parameters have the same name.

Post Type:Core Java Tutorial
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

What is this keyword in Java?

The keyword “this” in Java represents the current instance of a class. It is mainly used to access other members of the same class, such as methods, fields, and constructors.

this Keyword Use in Java

The whole point of using this keyword is to differentiate between a class’s formal parameter and data members. If they are the same, it causes ambiguity. To avoid this confusion, data members of a class must be preceded by the “this” keyword.

We can use this keyword in two ways:

  • this
  • this()

this: this keyword in Java is used to differentiate variables of the class and formal parameters of methods or constructors. Not only does it always point to the current class object, but it can also help make your code more readable and organized.

The syntax for this is:

this.data member of the current class

Note: If a variable is preceded by “this,” JVM treats it as a class variable.

this(): This is a great way to avoid creating multiple objects for the same class. You can use it to call one constructor from another without creating the objects multiple times.

If you write

  • this() – then this will call the default constructor
  • this(val1, val2,…) – this will call the parameterized constructor.

Until this, we have learned what this keyword is and where to use it. but now we will discuss where we can use this keyword in detail.

this Keyword Usage in Java

Here are some of this keyword usage in Java:

  • Refer to the current class instance variable.
  • Invoke Current Class Method
  • Invoke the Current Class Constructor
  • Pass as an Argument in the Method
  • Passing as an Argument in the Constructor call
  • Return Current Class Instance

Refer to the current class instance variable

This keyword is used to refer to the current class instance variable. If there is ambiguity between the instance variables and parameters, using this keyword will resolve that problem.

Before using this keyword, let us try to understand the problem you will face:

package com.softwaretestingo.basic;
class ex11
{  
	int rollno;  
	String name;  
	int fee;  
	ex11(int rollno,String name,int fee)
	{  
		rollno=rollno;  
		name=name;  
		fee=fee;  
	}  
	void display()
	{
		System.out.println(rollno+" "+name+" "+fee);
	}  
}  
public class WithOutThisKeywordEx1 
{
	public static void main(String[] args) 
	{
		ex11 obj=new ex11(123, "Testing", 7895);
		obj.display();
	}
}

Output:

0 null 0

In the above example, the instance variable and parameter variable names are the same. So, in such cases, ambiguity occurs, and because of this, we are not getting the expected result.

But now, let us use this keyword to differentiate between the instance variable name and parameter variable and see the result.

package com.softwaretestingo.basic;
package com.softwaretestingo.thiskeyword;
class ex1
{  
	int rollno;  
	String name;  
	int fee;  
	ex1(int rollno,String name,int fee)
	{  
		this.rollno=rollno;  
		this.name=name;  
		this.fee=fee;  
	}  
	void display()
	{
		System.out.println(rollno+" "+name+" "+fee);
	}  
}  
public class ThisKeywordEx1 
{
	public static void main(String[] args) 
	{
		ex1 obj=new ex1(123, "Testing", 7895);
		obj.display();
	}
}

Output:

123 Testing 7895

Note: If the instance variable name and local variable names are different, then there is no need to use this keyword.

Invoke Current Class Method

This keyword can be used to invoke methods of the current class. If this keyword is not used, the compiler automatically adds it when invoking the method.

package com.softwaretestingo.thiskeyword;
class ex2
{  
	void ex21() 
	{
		System.out.println("Inside Print Ex21");
	}
	void ex22() 
	{
		System.out.println("Inside Print Ex22");
		ex21();
		this.ex21();
	}

}  
public class ThisKeywordEx2 
{
	public static void main(String[] args) 
	{
		ex2 obj=new ex2();
		obj.ex22();
	}
}

Output:

Inside Print Ex22
Inside Print Ex21
Inside Print Ex21

Invoke the Current Class Constructor

If you want to use this() constructor call, it can be used to invoke the current class constructor. This is helpful if you want to reuse a constructor or if you need to do some constructor chaining.

package com.softwaretestingo.thiskeyword;
class ex3
{  
	ex3()
	{
		System.out.println("Default Constructor Of Class Ex2 Called");
	}
	ex3(int a)
	{
		// this() should always the first statement otherwise you will get errors
		this();
		System.out.println("Parameterized Constructor Is Called & and the Value: "+a);
	}
}  
public class ThisKeywordEx3 
{
	public static void main(String[] args) 
	{
		ex3 obj=new ex3(2023);
	}
}

Output:

Default Constructor Of Class Ex2 Called
Parameterized Constructor Is Called & and the Value: 2023

Note: You can also call the parameter constructor from the default constructor.

Pass as an Argument in the Method

The keyword ‘this’ in Java is really useful! You can use it as an argument while calling a method, which comes in handy for event handling. For example, let’s say you have a program that needs to track events. Let’s see an example program

package com.softwaretestingo.basic;
package com.softwaretestingo.thiskeyword;
class ex4
{  
	void ab(ex4 t) 
	{ 
		System.out.println("Ab Method called"); 
	} 
	void ac()  
	{ 
		/* Passing this keyword as an argument in the ab method and it will 
		 * pass the reference of current class object to the ab method.
		 */
		ab(this);  
	} 
}  
public class ThisKeywordEx4 
{
	public static void main(String[] args) 
	{
		ex4 obj=new ex4();
		obj.ac();
	}
}

Output:

Ab Method called

Passing as an Argument in the Constructor call

We can use one object in multiple classes when we pass this keyword in the constructor call. This concept is useful when using an object in different contexts. This is a useful concept that can be applied in many situations. For example, let’s look at a program to see how this works.

package com.softwaretestingo.basic;
package com.softwaretestingo.thiskeyword;
class ex6
{  
	ThisKeywordEx5 obj;

	// Declare an Parameterized Constructor and pass object of Class ThisKeywordEx5
	ex6(ThisKeywordEx5 obj)
	{
		this.obj=obj;
	}
	void show() 
	{ 
		System.out.println("Show method is called"); 
		System.out.println("Value of b: " +obj.b); 
	} 
}  
public class ThisKeywordEx5 
{
	int b = 30;

	//Declare the Default Constructor
	ThisKeywordEx5()
	{
		/*Create an object of class ex5 and in that pass the current class (ThisKeywordEx5)
		 * object reference by passing the keyword this */
		ex6 ex=new ex6(this);
		ex.show();

	}
	public static void main(String[] args) 
	{
		ThisKeywordEx5 obj=new ThisKeywordEx5();
	}
}

Output:

Show method is called
Value of b: 30

Return Current Class Instance

We can return the keyword “this” as a statement from the methods. In that case, the return type of methods will be class type (non-primitive).

package com.softwaretestingo.thiskeyword;
class ex8
{  
	// Declare an Instance Method with return class type (ex8) 
	ex8 show()
	{
		return this;
	}
	void msg()
	{
		System.out.println("Displaying Message");
	}

}  
public class ThisKeywordEx6 
{
	public static void main(String[] args) 
	{
		new ex8().show().msg();
	}
}

Output:

Displaying Message

Conclusion:

In this blog post, we tried to cover all the possible uses of the think keywords in Java in detail with the example programs. If you still have questions, you can ask us in the comment section.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment