Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

this Keyword In Java – All You Need To Know

Last updated on Jun 19,2023 8.2K Views

A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.
19 / 72 Blog from Java Core Concepts

this is a keyword which represents an object in a method or a constructor. It is basically used to eliminate the confusion between class attributes and parameters with the same name. In this article, I will tell you the various aspects and uses of this keyword in Java.

Below are the topics that I will be covering in this article:

So, let’s get started!

What is this keyword in Java?

this keyword in Java represents the current instance of a class. It is mainly used to access other members of the same class. With the help of this keyword, you can access methods, fields, and constructors of the same class within the class.

Now, let’s move further and understand what is the need of this keyword in Java.

Why use this keyword in Java?

The main motto of using this keyword is to differentiate the formal parameter and data members of the class. If in case, the formal parameter and data members of the class are the same, then it leads to ambiguity. So, in order to differentiate between formal parameter and data member of the class, the data member of the class must be preceded by the “this” keyword.

Basically, “this” keyword can be used in two ways.

  1. this. 
  2. this()

1. this. 

It can be used to differentiate variable of the class and formal parameters of method or constructor. Not only that,  it always points to the current class object. Syntax of this keyword is as shown below:

Syntax

this.data member of the current class

Note: If there is any variable which is preceded by “this”, then JVM treats that variable as a class variable.

2. this() 

It can be used to call one constructor within another without creating the objects multiple times for the same class.

Syntax

this(); // call no parametrized or default constructor
this(value1,value2,.....) //call parametrized constructor

Now that you know what is this keyword and why do you need it, let’s dive deeper into this article and understand the various aspects where this keyword can be used in Java.

Uses of this keyword

There are 6 ways where this keyword can be used in Java. They are as follows:

  1. Used with a field
  2. Used to invoke a constructor
  3. Used to return the current class instance
  4. Used as a method parameter
  5. Used to invoke a current class method
  6. Used as an argument in the constructor call

Now, let’s get into the details of each of these methods.

1.  this keyword can be used with a field / Variable Hiding

this keyword can be very helpful in Variable Hiding. Here, you cannot create two instances/local variables with the same name. However, it is possible to create one instance variable and one local variable with the same name. In this case, the local variable will be able to hide the instance variable. This is called Variable Hiding. Now, let’s understand this in a more detailed manner with the help of an example.

package Edureka;
import java.util.*;
public class field {
int j, n;
// Parameterized constructor
Test(int j, int n)
{
this.j = j;
this.n = n;
}
void display()
{
//Displaying value of variables j and n
System.out.println("j = " + j + " n = " + n);
}
public static void main(String[] args) {
field obj = new field(27, 01);
obj.display();
}
}

Output:

j = 27 n = 01 

In the above example, formal arguments and instance variables are the same. Hence, to distinguish between these variables, I have used this keyword to output the local variables. So this was all about the variable hiding.

Now let’s see how this keyword in Java can be used to invoke a constructor.

2. this keyword can be used to invoke a constructor

this() constructor call can be used to call the current class constructor. It can be also used to reuse the constructor. You can also call this technique as constructor chaining. Let’s take a small example and understand how this() is used.

package Edureka;
import java.util.*;
public class Example {
{
int j, n;

//Default constructor
Example()
{
this(27, 01);
System.out.println("Inside default constructor n");
}

//Parameterized constructor
Example(int j, int n)
{
this.j = j;
this.n = n;
System.out.println("Inside parameterized constructor");
}

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

Output:

Inside parameterized constructor
Inside  default constructor

In the above example, you can see that “this” keyword is used to invoke an overloaded constructor in the same Class.

3. this keyword can be used to return the current class instance

Here, you can return this keyword as a statement from the method. In this case, return type of the method must be the class type. Let’s understand this with the help of an example.

public class Edureka {
int j, int n;
//Default constructor
Edureka(){
j = 100;
n = 200;
}
//Method that returns current class instance
Edureka get() {
return this;
}
//Displaying value of variables j and n
void display() {
System.out.println("j = " + j + " n = " + n);
}
public static void main(String[] args) {
Edureka obj = new Edureka();
obj.get().display();
}
}

Output:

j = 100, n = 200 

4. this keyword can be used as a method parameter

this keyword can be used inside the method in order to call another method from same class. Below example demonstrates the same.

public class Edureka {
int j, n;
// Default constructor
Edureka()
{
j = 100;
n = 200;
}
// Method that receives 'this' keyword as parameter
void display(Edureka obj) {
System.out.println("j = " + j + " n = " + n);
}
// Method that returns current class instance
void get()
{
display(this);
}
public static void main(String[] args) {
Edureka obj = new Edureka();
obj.get();
}
}

Output:

 j = 100, n = 200 

5. this keyword used as a current class method

this keyword can be used to invoke the method of the current class. Let’s understand that with the help of an example.

pubic class Edureka {
void display(){
//calling fuction show()
this.show();
System.out.println("Inside display function");
}
void show() {
System.out.println("Inside show funcion");
}
public static void main(String args[]) {
Edureka j = new Edureka();
j.display();
}
}

Output:

Inside show funcion
Inside display function

6. this keyword is used as an argument in the constructor call

You can pass this keyword in the constructor also. It is useful if you have to use one object in multiple classes. Now let’s understand the same with the help of an example.

public class Y{
X obj;

// Parameterized constructor with object of X
// as a parameter
Y(X obj) {
this.obj = obj;
// calling display method of class X
obj.display();
}
}
class X{
int x = 45;
// Default Contructor that create a object of Y
// with passing this as an argument in the
// constructor
X(){
Y obj = new Y(this);
}
// method to show value of x
void display(){
System.out.println("Value of x in Class X : " + x);
}

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

Output:

Value of x in Class X : 45

So, this is how you can use this keyword as an argument in the constructor call. That was all about the various uses of this keyword in Java. Now let’s see some of the important factors of using this keyword.

Important factors of this keyword:

  1. You can’t use super and this keyword in a static method and in a static initialization block even though you are referring static members.

  2. You should call super() and this() calling statements inside the constructors only and they must be the first statement in the constructors.

This brings us to the end of the article on this keyword in Java.  I hope you found it informative.

Build real-world apps from scratch and showcase your skills with our hands-on Flutter APP Development Course.

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this “this keyword in Java ”article and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

this Keyword In Java – All You Need To Know

edureka.co