This Keyword in Java with Examples

The “this keyword in Java is a reference variable that refers to the current class object. In other words, it holds a reference to the object whose method or constructor is currently being executed.

The current class object can be referred to using the “this” reference anywhere within an instance method or constructor of the class. The keyword “this” can be applied to instance variables, constructors, and instance methods.

You can use this keyword within instance methods, constructors, and instance initialization blocks of a class. In simple words, it can be used only within an instance context of a class and cannot be referenced directly from outside the class.

How to Use the this Keyword in Java?


The general syntax to use the ‘this’ keyword in Java programming is:

this.a;  
this.msg(); 
this(int a);

In the above syntax:

  • this.a: Refers to the instance variable a of the current object.
  • this.msg(): Calls the instance method msg() of the current object.
  • this(int a): Calls another constructor of the same class.

Prove that this Keyword Refers to Current Class Object


Example 1: this Keyword Refers to the Current Object

Let’s take an example program where we will prove that the keyword ‘this’ refers to the current class object or not.

public class Hi 
{ 
  void msg() 
  { 
    System.out.println(this); // It will print the same reference ID. 
  } 
public static void main(String[] args) 
{ 
// Create an object of class Hi.
   Hi h = new Hi(); 
   System.out.println(h); // It will print the reference ID. 
   h.msg(); 
 } 
}

Output:

thisKeyword.Hi@1db9742 
thisKeyword.Hi@1db9742

As you can see in the output of the above program, the address of this and the object reference variable are the same. This shows that this keyword in Java refers to the current class object.

Use of This keyword in Java


In Java, there are six usages of this keyword. They are as follows:

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke the current class instance (non-static) method.
  • this() can be used to invoke another constructor of the current class.
  • this can be passed as an argument in a method call.
  • this can be passed as an argument in a constructor call.
  • this can be used to return the current class object from a method.

Referring to the Current Class Instance Variable Using this Keyword in Java


The “this” keyword can be used to refer to the current class instance variable in Java. If there is an ambiguity between instance variables and parameters, this reference can resolve the problem of ambiguity.

Example 2: Understanding Problem without using this Keyword

Let’s take an example program to understand the problem of ambiguity that arises when the this keyword is not used.

public class Student 
{ 
// Declare instance variables. 
   String name; 
   int rollno; 

// Declare a parameterized constructors with two parameters name and rollno. 
// Here, name and rollno are local variables. 
   Student(String name, int rollno) 
   { 
   // Here, the parameter's identifier is the same as that of the instance variables name. 
      name = name; 
      rollno = rollno; 
   } 
   void display() 
   { 
      System.out.println(name+ " "+rollno); 
   } 
public static void main(String[] args) 
{ 
 // Create an object of class Student and call the display() method using reference variable s. 
    Student s = new Student("DEEPAK", 123); 
    s.display(); 
 } 
}

Output:

null 0

In this example program, the parameter’s identifiers (formal arguments) are the same as the names of the instance variable. Java allows this. However, when parameter names and instance variable names are identical, the parameters hide the instance variables within the constructor.

As a result, statements such as name = name; assign the parameter to itself rather than assigning the value to the instance variable. This problem can be resolved by using the this keyword in Java.

Example 3: With the Use of this Keyword

public class Student 
{ 
// Declare instance variables. 
   String name; 
   int rollno; 

// Declare a parameterized constructor with two parameters name and rollno. 
// Here, name and rollno are local variables. 
   Student(String name, int rollno) 
   { 
   // Here, the parameter names are the same as the names of instance variables. 
   // So, we will use this keyword to differentiate between instance variables and parameters. 
      this.name = name; // Reference to current object. 
      this.rollno = rollno; // Reference to current object. 
    } 
    void display() 
    { 
       System.out.println(name+ " "+rollno); 
    } 
public static void main(String[] args) 
{ 
 // Create an object of class Student and call the display() method using reference variable s. 
    Student s = new Student("DEEPAK", 123); 
    s.display(); 
 } 
}

Output:

DEEPAK 123

In this example, when the statement new Student(“DEEPAK”, 123) is executed, Java creates a new Student object. Inside the constructor, the this keyword refers to that newly created object.

In the parameterized constructor of the Student class, this.name and this.rollno refer to the instance variables of the current object. The this keyword helps distinguish the instance variables from the constructor parameters having the same names.

Since the parameter names and instance variable names are identical, we must use the this keyword to access the instance variables.

Note:

If the parameter names (local variables) and instance variable names are different, there is no ambiguity. So, using this keyword is optional.

Calling a Current Class Method Using the this Keyword


We can use this keyword to invoke an instance method of the current class. When we do not specify an object reference variable to call an instance method, the Java compiler implicitly uses this to refer to the current object.

Therefore, a method call such as m(); is treated as this.m1(); by the compiler. Look at the diagram below.

Java implicitly invokes the method on the current object (this).

Example 4: Invoking a Current Class Method Using this Keyword

Let’s take an example program in which we invoke a current class method using the this keyword. When an instance method is called without an explicit object reference, Java implicitly invokes it on the current object. Therefore, the statement m(); is equivalent to this.m();.

public class Hello 
{ 
   void m() 
   {  
      System.out.println("Hello Java"); 
   } 
   void n() 
   { 
      m(); // method m() is called. m() is same as this.m(). Compiler automatically put this here. 
      System.out.println("Welcome you"); 
   } 
public static void main(String[] args) 
{ 
    Hello obj = new Hello(); 
    obj.n(); 
 } 
}

Output:

Hello Java 
Welcome you

Example 5: Returning the this Reference from a Method

Let us consider an example program in which we will return this keyword from the method in Java.

public class AddTest 
{ 
 // Declare an instance variable num of data type int. 
    int num; 

 // Declare one parameter constructor with parameter num. The parameter num is a local variable. 
    AddTest(int num) 
    { 
       this.num = num; // Reference to current object. 
    } 
 // Declare an instance method. 
    void show() 
    { 
       System.out.println("Number: " +this.num); 
    } 
 // Declare an instance method incr() with type class 'AddTest'. 
    AddTest incr() 
    { 
       num++; // Increment by 1. 
    // Returns this reference to the current object. 
       return this; 
    } 
public static void main(String[] args) 
{ 
  // Create an object of the class and pass argument 20 to its parameterized constructor. 
     AddTest add = new AddTest(20); 

  // Call incr() method using reference variable add and increment two times. 
     add.incr().incr(); // Call show() method using reference variable add. 
     add.show(); 
  } 
}

Output:

Number: 22

In this example, the incr() method returns a reference to the current object using the this keyword. When the statement add.incr().incr(); is executed, the first call to incr() method increments the value of num from 20 to 21 and returns a reference to the current object.

Since the method returns the same object, the second incr() method is immediately invoked on that object, incrementing num from 21 to 22.

After both method calls are completed, the show() method is invoked using the reference variable add, which displays the updated value: Number: 22.

This technique is known as method chaining, where a method returns the current object so that another method can be called on the same object.

Calling a Current Class Constructor Using the this Keyword in Java


In Java, we can use this keyword to invoke another constructor of the same class from within a constructor. This is called an explicit invocation constructor. This technique is used for constructor chaining in Java. A call to another constructor using this() must be the first statement in a constructor. This means we cannot add this keyword anywhere other than the first line of the constructor.

The Java compiler does not automatically insert this(). However, if a constructor does not explicitly invoke another constructor using this() or a superclass constructor using super(), the compiler automatically inserts super() as the first statement.

Recursive constructor invocation using this() is not allowed in Java because it results in a compile-time error. For example:

class Test {
    Test() {
        this(); // Compile-time error
    }
}

Example 6: Calling a Default Constructor from Parameterized Constructor:

class ABC 
{ 
// Declare a default constructor. 
   ABC() 
   { 
     System.out.println("Hello, John"); 
   } 
// Declare a parameterized constructor with parameter x. Here, x is a local variable. 
   ABC(int x) 
   { 
  // This statement calls default constructor from parameterized constructor. 
     this(); // Must be the first line in the constructor. 
     System.out.println("Welcome, India"); 
   } 
} 
public class ABCTest 
{ 
  public static void main(String[] args) 
  { 
 // Create an object of class ABC and pass the value to parameterized constructor. 
    ABC obj = new ABC(12); 
  } 
}

Output:

Hello, John
Welcome, India

In the main method of class ABCTest, when an object is created for class ABC by passing an argument of 12, it calls the parameterized constructor of class ABC. The keyword “this” in the first line of the constructor calls the default constructor of class ABC and prints the output “Hello, John” on the console.

After the default constructor completes execution, control returns to the parameterized constructor, which then prints “Welcome, India”.

Example 7: Calling a Parameterized Constructor from Default Constructor

class CD 
{ 
   CD() 
   { 
      this(5); // This statement will call parameterized constructor from default constructor. 
      System.out.println("Hello, John"); 
   } 
   CD(int x) 
   { 
      System.out.println(x); 
      System.out.println("You are so sweet."); 
   } 
} 
public class CDclasstest 
{ 
  public static void main(String[] args) 
  { 
     CD cd = new CD(); // This statement will call default constructor.
  } 
}

Output:

5 
You are so sweet. 
Hello, John

In this example, we have defined a class CD, which contains two constructors – a default constructor and a parameterized constructor. In the default constructor, we can see that there is a call to the parameterized constructor using the “this” keyword and passing the value 5 as an argument. This is known as constructor chaining.

After the call to the parameterized constructor, the System.out.println(“Hello, John”); statement will execute, which will print “Hello John” to the console. The parameterized constructor has an integer parameter x. Inside this constructor, the value of x is printed to the console, followed by the message “You are so sweet.”

Inside the main method, we have created an instance of the CD class. The default constructor of the CD class invokes while creating an object of the class CD. The default constructor of the CD class calls the parameterized constructor by passing the value 5 and then prints “Hello, John” to the console.

Important Note:

A constructor can contain either a this() call or a super() call as its first statement, but not both at the same time.

Passing this Keyword as an Argument to a Method call


The keyword ‘this’ in Java can be used as an argument while calling the method. It is mainly used in event handling. Let’s take an example program to understand the concept.

Example 8: Passing this Keyword as an Argument to Method Call

public class Test 
{ 
// Declare an instance method with a parameter t of type class. 
   void m1(Test t) 
   { 
      System.out.println("m1 method is called"); 
   } 
   void m2()  
   { 
     // Passing this as an argument in the m1 method. 
     // this keyword passes the reference of current class object to the m1 method. 
      m1(this); 
   } 
   public static void main(String[] args) 
   { 
       Test t = new Test(); 
       t.m2(); // m2 method is called. 
   } 
}

Output:

m1 method is called

Passing This Keyword as an Argument in Constructor Call


You can also pass this keyword in the constructor call. This concept is useful when you have to use one object in multiple classes. Let’s take an example program to understand it better.

Example 9: Passing this as an Argument in Constructor Call

class A 
{ 
   B obj; 
// Declare a parameterized constructor with a parameter obj of type class. 
   A(B obj) 
   { 
      this.obj = obj; 
   } 
   void show() 
   { 
      System.out.println("Show method is called"); 
      System.out.println("Value of b: " +obj.b); 
   } 
} 
public class B 
{ 
 // Declare an instance variable and initialize the value 30. 
    int b = 30; 

 // Declare a default constructor. 
    B() 
    { 
    // Create an object of class A and pass this as an argument to call the constructor of class A. 
    // this keyword passes the reference of the current class object. Here, B is the current class object. 
       A a = new A(this); 
       a.show(); // show() method of class A is called. 
     } 
     public static void main(String[] args) 
     { 
        // Create an object of class B.
        B obj = new B(); 
     } 
}

Output:

Show method is called 
Value of b: 30

Return Current Class Object Using this Keyword


You can return this keyword as a statement from the method. In such a case, the return type of method must be class type (non-primitive). The general syntax to return this keyword is as follows:

return_type method_name()
{
   return this;
}

Example 10: Return this Keyword

Let us consider an example in which we will return the current class object using the “this” keyword in Java.

public class Animal 
{ 
// Declare an instance method show with return type Animal (class type). 
   Animal show() 
   { 
      return this; // return statement
   } 
   void msg() 
   { 
      System.out.println("Lion is an animal"); 
   } 
public static void main(String[] args) 
{ 
    new Animal().show().msg(); 
 } 
}

Output:

Lion is an animal

In this example, we have created a class named Animal, which contains three methods, show(), msg(), and a main() method. The show() method is declared with a return type of Animal, which means it returns an instance of the Animal class.

Inside the show() method, the return statement refers to the current instance of the class (Animal in this case). So, when the show() method is called, it returns the current instance of the Animal class. The msg() method is a simple method that prints “Lion is an animal” to the console.

In the main method, we have created a new instance of the Animal class and then immediately called the show() method on that instance using the dot notation.

This returns the same instance (since the show() method returns this, which is the current instance). After calling the show() method, the msg() method will call on the same instance, which will print “Lion is an animal” to the console.

Can We Use this and super Keywords in a Static Context?


No, we cannot use the this keyword in a static context, such as static methods and static initialization blocks. This is because static members belong to the class itself rather than to any particular object. Since this refers to the current object, there is no current object available in a static context.

Similarly, the super keyword also cannot be used in a static context because it refers to the parent class part of the current object. Attempting to use this or super in a static context results in a compile-time error.

Example 11: Using this in a Static Method

class Test {
    int x = 10;

    static void display() {
        System.out.println(this.x); // Compile-time error
    }
    public static void main(String[] args) {
        display();
    }
}

Example 12: Using super in a Static Method

class Parent {
    int x = 10;
}

class Child extends Parent {
    static void display() {
        System.out.println(super.x); // Compile-time error
    }
    public static void main(String[] args) {
        display();
    }
}

Advantages of This Keyword in Java


There are several benefits of using this keyword in Java. They are:

  • By using “this,” we can prevent confusion and ambiguity between instance variables and method parameters with the same name.
  • The use of the “this” keyword improves the readability of the code by clearly indicating which variables belong to the class instance. This makes the code more understandable.
  • The “this” keyword helps when chaining methods within the same object, maintaining a consistent reference to the instance and ensuring seamless method calls.
  • While using multiple constructors in a class, “this” simplifies the process of constructor overloading and initialization of different attributes.
  • Explicit use of the keyword “this” contributes to better code maintenance over time. It helps us easily identify where instance variables are being used.

In this tutorial, you learned this keyword in Java and its different uses with the help of examples. I hope that you will have understood the basic syntax and concepts of this keyword. Stay tuned for the next tutorial.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.