×

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java.

In Java, the term "this" refers to a reference variable. The reference variable "this" in the Java program refers to the current object. As a result, if you wish to access any member or function of the current object, use the 'this' reference. Because it links to the current object, the reference 'this' is sometimes referred to as a 'this pointer.' When the class attributes and arguments have names, the 'this pointer' is beneficial. When such a circumstance happens, the 'this pointer' solves the uncertainty because it allows us to access parameters.

Use of “this” keyword:

  • “this" can be used to refer current class instance variable.
  • “this” can be used to invoke current class method(implicitly)
  • “ this () ” can be used to invoke current class constructor.
  • “ this ” can be passed as an argument in the method call.
  • “ this ” can be passed as argument in the constructor call.
  • " this ” can be used to return the current class instance from the method.

Access instance variable using “this” keyword:

The keyword this can be used to refer to the current class instance variable. If there is any discrepancy between the instance variables and arguments, this keyword resolves it.

Consider the following java program to access instance variable using “this” keyword.

import java.io.*;
import java.util.*;




class Solution
{
     int var1 ;
     int var2 ;
 
    Solution ( int var1 , int var2 )
    {
        this.var1 = var1 + var1 ;
        this.var2 = var2 + var2 ;
    }
 
   void displayMeth ( )
    {
          System.out.println ( " Value of var1 is = " + var1 + " Value of var2 is = " +  var2 ) ;
    }
}
 
class ThisTest {
 
       public static void main ( String [ ] args )
       {
Scanner sc = new Scanner ( System.in ) ;
System.out.println ( " Enter the value of variable v : " ) ;
  int v = sc.nextInt ( ) ;
System.out.println ( " Enter the value of variable v1 : " ) ;
  int v1 = sc.nextInt ( ) ;
            Solution obj = new Solution ( v , v1 ) ;
            obj.displayMeth ( ) ;
       }
}

Output:

this keyword in Java

The instance variables and method arguments in the preceding program have the same names. We use the 'this' pointer with instance variables to distinguish between them and method arguments.

In the above example, parameters (formal arguments) and instance variables are the same. As a result, we use this term to distinguish between local variables and instance variables.  “this” pointer can also be sent as a method argument. When working with events, passing this pointer as a method argument is frequently essential. For example, if you wish to initiate an event on the current object/handle, you must use “this” reference to do so.

class Test_method
{
    int val1;
    int val2;
 
    Test_method()
    {
        val1 = 10;
        val2 = 20;
    }
 
    void printVal(Test_method obj)
    {
             System.out.println("val1 = " + obj.val1 + "  val2 = " + obj.val2);
    }
 
    void get()
    {
           printVal(this);
    }
}
 
class Main{
    public static void main(String[] args)
    {
        Test_method object = new Test_method();
        object.get ( ) ;
    }
}

In this program, we create an object of the class Test method in the main function and then use the get() method using this object. Within the get () function, the 'this' pointer is provided to the printVal () method, which displays the current instance variables.

“this” can be used to invoke current class method(implicitly) :

You may use this reference to activate a method just as you can send it to the method. If you neglect to include this reference while executing the current class's method, the compiler inserts it for you.

Test2.java:

class TestThis2 {
 
    void printMet ( )
    {
        
       this.showThis ( ) ;
 
       System.out.println ( " TestThis2 : = :  printMet " );
    }
 
    void showThis ( )
   {
        System.out.println ( " TestThis2 : = : showThis " ) ;
    } 
}
 
class Test2
{    
    public static void main ( String args [ ] ) 
{
        TestThis2 this1 = new TestThis2 ( ) ;
        this1.printMet ( ) ;
    }
}

Output :

this keyword in Java

When the class object in the main function invokes the class method printMet(), it uses this pointer to call the showThis() method.

“this()” can be used to invoke current class constructor :

To invoke the current class function Object () { [native code] }, use the this() function Object() { [native code] } call. It allows you to reuse the function Object () { [native code] }. In other words, it is used to link constructors.

ThisConstInvoke.java :

class ThisConst
{
     int var1 ;
     int var2 ;
 
    ThisConst ( )
    {   
        this ( 20 , 23 ) ;
        System.out.println ( " This is a Default constructor \n " ) ;
       
    }
 
    
   ThisConst ( int var1 , int var2 )
    {
        this.var1 = var1 ;
        this.var2 = var2 ;
        System.out.println ( " This is a Parameterized constructor " ) ;
        System.out.println ( var1+ " " + var2 ) ;
    }
}
 
class ThisConstInvoke {
    public static void main ( String [ ] args )
    {
         ThisConst object = new ThisConst ( ) ;
    }
}

Output:

this keyword in Java

this can be passed as an argument in the method call :

The term this can also be used as an argument in a method. It is mostly used in event management. Consider the following example:

Test2.java :

class Test2
{  
  void met ( Test2 object )
  {  
      System.out.println ( " method met is being  invoked " ) ;  
  }  
  void metCall ( ) 
  {  
     met ( this ) ;  
  }  
  public static void main ( String args [ ] ) 
  {  
     Test2 obj1 = new Test2 ( ) ;  
     obj1.metCall ( ) ;  
  }  
}  

Output :

this keyword in Java

this can be passed as argument in the constructor call :

This keyword can also be sent to the function Object() { [native code] }. It comes in handy when we need to utilize the same object in numerous classes. Consider the following example:

ConCall.java :

class Call {  
  ConCall obj1 ;  
  Call ( ConCall obj1 )
  {  
    this.obj1 = obj1 ;   
  }  
  void displayCall ( ) 
  {  
    System.out.println ( " Access the data member of class ConCall \n " + obj1.dat )  ;  
  }  
}  
  
class ConCall
{  
   int dat = 2023 ;  
   ConCall ( )
   {  
      Call b = new Call ( this ) ;  
      b.displayCall ( ) ;  
    }  
   public static void main ( String args [ ] )
   {  
     ConCall a = new ConCall ( ) ;  
   }  
}  

Output :

this keyword in Java

this can be used to return the current class instance from the method :

The method can output this keyword as a statement. In this situation, the method's return type must be the specific class (non-primitive). Consider the following example:

RetCall.java

class Test1 
{  
  Test1 getA ( )
  {  
    return this ;  
  }  
  void outMsg ( )
  {
     System.out.println ( " Hello progrmmer ! welcome to this keyword " ) ;
   }  
}  


class RetCall
{  
   public static void main ( String args [ ] )
   {  
   new Test1 ( ).getA( ).outMsg ( ) ;  
   }  
}  

Output :

this keyword in Java

Proving “this” keyword :

Let's show that this keyword corresponds to the variable in the current class instance. We are printing the reference variable in this program, and the output of both variables is the same.

ProveThis.java :

class ProveThis
{  
    void metProof ( )
    {  
         System.out.println ( this ) ; 
    }  
    public static void main ( String args [ ] )
    {  
         ProveThis obj2 = new ProveThis ( ) ;  
         System.out.println ( obj2 ) ;  
         obj2.metProof ( ) ;  
     }  
}  

Output :

this keyword in Java

Related Topics

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.