×

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

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.