This Keyword in Java | Use & Example

This Keyword in Java


this keyword in Java is a reference variable that refers to the current class object. In other words, it holds the reference to the current class object or same class object.

The current class object can be referred by using this reference to anywhere in the class. The keyword “this” in Java program can be applied to instance variables, constructors, and methods.

It is used only inside the class i.e only inside the member functions of the class and can only be used within non-static function of class. This reference cannot be used outside the class.

The syntax to use ‘this’ keyword in Java program is as follows:

Syntax:

this.a;  // It calls current class instance variable where a is an instance variable.
this.msg(); // It calls current class instance method where msg() is an instance method.
this(int a);  // To call parameterized constructor of current class object.

Note: this and super keyword cannot be used in a static method and static initialization block. This will give compile-time error.

Prove that this keyword refers to Current class object


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

Program source code 1:

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

As you can see in the output of the above program, the address of this and 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


There are six usages of Java this keyword. They are as follows:
1. this reference can be used to refer to the current class instance variable.
2. this keyword is used to call the non-static method of the current class.
3. this() can be used to invoke the current class constructor.

4. this keyword can be used as a parameter in the method call.
5. The keyword “this” can be used as a parameter in the constructor call.
6. It can also be used to return the object of the current class from the method.

Referring current class instance variable using this keyword in Java


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

Understanding problem without using this keyword

Let’s take an example program to understand the problem of ambiguity that will occur in the below program.

Program source code 2:

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

// Declare two parameterized constructors such as 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 the above example program, the parameter’s identifier (formal arguments) is the same as that of the instance variable. It is permissible to do this in java.


But, there occurs the problem of ambiguity between parameters and instance variables. So, we can resolve this problem by using this keyword in java programming.

 

Solution to solve the above problem using this keyword

Program source code 3:

public class Student 
{ 
// Declare instance variables. 
   String name; 
   int rollno; 
// Declare a parameterized constructor with two parameters such as name and rollno. Here, name and rollno are local variables. 
   Student(String name, int rollno) 
   { 
// Here, the parameter's identifier is same as that of the instance variables name. 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 the main method, the object reference variable ‘s’ is the current object in context. So, this reference stores the reference of object reference variable s.

In the parameterized constructor of class Student, this.name and this.rollno refers to data field of the current class object s. Here, the current class object means same class object. They can also be written without using this keyword.

But as the parameters (local variables) of instance method are having the same name as instance variables of class, we have to use the keyword this.

Note: If local variables (formal arguments) and instance variables are different, there is no need to use keyword ‘this’. For more detail, follow this tutorial: Constructor in Java.

Calling current class method using this keyword


The keyword ‘this’ can be used to call method of the current class. If you do not write ‘this’ keyword, the compiler automatically adds ‘this’ keyword while invoking the method. The following example in the figure shows how to add ‘this’ keyword automatically by the compiler while calling method.

Calling current class methods using this keyword in Java

Let’s create a program where we will call the current class method using this keyword. JVM will automatically put “this” keyword while calling method.

Program source code 4:

package thisKeyword; 
public class Hello 
{ 
/** * this keyword is used to call current/same class method. */
 void m() 
 { 
   System.out.println("Hello Java"); 
 } 
void n() 
{ 
  m(); // method m() is called. m() is same as this.m(). JVM 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

Returning this reference to Method in Java

Let’s take an example program in which we will return this keyword to the method.
Program source code 5:

package thisKeyword; 
public class AddTest 
{ 
// Declare an instance variable num with 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 one parameter 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

The method incr() returns a reference to the current object. Inside the main method, when add.incr is called using reference variable add, num is incremented to 21 and the reference of the current object is returned which again calls the incr() method. This is done two times.

So, number becomes 22. In the end, the show method is called using the reference variable which displays the number: 22.

Calling current class constructor using this keyword in Java


this() keyword in Java can also be used to call another current class constructor from within a constructor. This is called an explicit invocation constructor. It is used for constructor chaining.

Key Points to Remember:

1. The invocation of another constructor using ‘this’ keyword must be the first line of constructor only. That means we cannot add this() keyword anywhere other than the first line of the constructor.
2. JVM never put automatically this keyword like super.
3. Recursion using ‘this’ call to the constructor is not allowed in Java.

Let’s take some example programs based on this concept.

Calling default constructor from parameterized constructor

Program source code: 6

package thisKeyword; 
public class ABC 
{ 
// Declare a default constructor. 
   ABC() 
   { 
     System.out.println("HELLO JOHN"); 
   } 
// Declare a parameterized constructor with parameter x. x is a local variable. 
   ABC(int x) 
   { 
     this(); // Must be the first line in the constructor. // Calling default constructor from parameterized 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 with passing an argument 12, it calls parameterized constructor of class ABC. The keyword this in the first line of the constructor will call default constructor of class ABC and prints the output “HELLO JOHN” on the console.

After printing the first output, the control of execution again comes to the parameterized constructor and prints the output “WELCOME INDIA”.

Calling parameterized constructor from default constructor

Program source code 7:

package thisKeyword; 
public class CD 
{ 
 CD() 
 { 
   this(5); // Calling 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(); 
  } 
}
Output: 
       5 
       You are so sweet 
       Hello John

Passing this keyword as an argument in Method call


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

Program source code 8:

package thisKeyword; 
public class Test 
{ 
// Declare an instance method whose a parameter is t with class type Test. 
   void m1(Test t) 
   { 
      System.out.println("m1 method is called"); 
   } 
 void m2()  
 { 
   m1(this); // Passing this as an argument in the m1 method. this keyword will pass the reference of current class object to the m1 method. 
 } 
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.

Program source code 9:

package thisKeyword; 
public class A 
{ 
   B obj; 
// Declare a parameterized constructor whose parameter is obj with class type B. 
   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 with initialization the value equal to 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 will pass 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) 
 { 
     B obj = new B(); 
   } 
 }
Output: 
       Show method is called 
       Value of b: 30

Return current class object using this keyword in Java


The keyword ‘this’ can be returned as a statement from the method. In such a case, the return type of method must be class type (non-primitive).

The following syntax can be used as a returned statement:
Syntax:

return_type method_name()
{
return this;
}

Program source code 10:

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

Recommended Post

Difference between this and super keyword in Java

Hope that this tutorial has covered almost all important topics related to this keyword in Java with example programs. I hope that you will have understood and enjoyed programming related to this keyword.
Thanks for reading!!!Next ⇒ Method overloading in Java⇐ PrevNext ⇒

Leave a Comment