• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Java Program
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » This Keyword In Java

This Keyword In Java

Last Updated on: August 18, 2022 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • What is this keyword in Java?
  • this Keyword Use in Java
  • this Keyword Usage in Java
  • Refer current class instance variable
  • Invoke Current Class Method
  • Invoke Current Class Constructor
  • Pass as an Argument in the Method
  • Passing as Argument in Constructor call
  • Return Current Class Instance

There are a lot of keywords in Java, like static, final, this, super, etc. In this post, we 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 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 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 parameters of a method have the same name.

Post Type:Core Java Tutorial, Java Programs 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 the formal parameter and data members of a class. 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 there’s a variable that’s preceded by “this,” then 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 having to create 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 is this keyword and where we can use this keyword. but no 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 current class instance variable
  • Invoke Current Class Method
  • Invoke Current Class Constructor
  • Pass as an Argument in the Method
  • Passing as Argument in Constructor call
  • Return Current Class Instance

Refer 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 how 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, both instance variable name and parameter variable name 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;
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, then the compiler will automatically add it when invoking the method.

package com.softwaretestingo.basic;
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 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.basic;
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(2022);
	}
}

Output:

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

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

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 when you’re doing 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;
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:

m1 method is called

Passing as Argument in Constructor call

When we pass this keyword in the constructor call, it allows us to use one object in multiple classes. This concept is useful when we need to use 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;
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.basic;
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 use of the think keywords in Java in detail with the example programs. If still you have any questions then you can ask us in the comment section.

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers