×

Java this keyword

This Keyword in Java

This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the term "this" refers to a reference variable that points to the active object in a method or function Object () {[native code]}. This keyword's primary use in Java is to clear up any ambiguity regarding class attributes and parameters with the identical names.

A reference variable in Java is denoted by the term "this." In a Java application, the reference variable "this" refers to the active object. Therefore, you can use the "this" reference to access any member or function of the current object. Given that it refers to the currently selected object, the reference "this" is sometimes known as a "this pointer." When the class attributes and arguments have names, the "this pointer" is helpful. When this happens, the "this pointer" clears out the complication because we may access parameters with the "this" pointer. In a method or function Object () {[native code]}, this keyword refers to the current object.

This keyword is most frequently used to avoid misunderstanding between class attributes and parameters with the same name (because a class attribute is shadowed by a method or function Object () {[native code]} parameter). In the example, the output would be "0" rather than "5" if the keyword were left out.

The word "this" has the following applications in Java:

  • To access the class instance variable, use the reference "this."
  • Even 'this' can be passed as an argument when calling a method.
  • The current class method can also be called automatically by using the 'this' keyword.
  • Use "this" if you want the method to return the current object.
  • 'this' can be used to call the current class's function Object () {[native code]}.
  • The argument "this" can also be passed to the function Object () {[native code]}.

1. this: to refer current class instance variable:

The current class instance variable can be referred to using this keyword. This keyword solves the ambiguity issue if there is any between the instance variables and parameters. Class and method parameters' instance variables may share the same name. The uncertainty that results from this can be resolved by using the "this" pointer.

The Java program that follows shows how instance variables can be accessed using the 'this' keyword.

Example 1:

class thisT
{
     int m;
     int n;
    //constructor of parameter
    this_T(int val1, int val2)
    {
        this.m = m + m;
this.n = n + n;
    }
   void disp()
    {
          System.out.println("Value1m = " + m + " Value2 = " + n);
    }
}
class Main{
       public static void main(String[] s)
       {
            this_T ject = new this_T(5,10);
ject. disp();
       }
}

Output:

Value1m = 10
Value2 n = 20

Example 2:

class Stud{  
int rno;
String name of stu;
float fee;
Stud(int rno,String name of stu,float fee){  
this.rno=rno;
this.name of stu=name of stu;
this.fee=fee;
}  
void disp(){System.out.println(rno+" "+name of stu+" "+fee);}  
}  
class TThis2{  
public static void main (String s []) {
Stud st=new Stud(5h5,"raju",5000f);
Stud st1=new Student(5h4,"deepu",6000f);
st. disp ();
st1.disp();
}}  

Output:

5h5raju 5000.0
5h4deepu 6000.0

It is unnecessary to use this keyword if local variables (also known as formal arguments) and instance variables disagree, as in the following program. You can see that the instance variables and method arguments in the example have the same names. To distinguish between instance variables and method parameters, we utilize the "this" pointer with instance variables.

2. this: to invoke current class method:

Using this keyword, you can call a method of the current class. If this keyword is not used, the compiler will automatically add it when calling the method. I'll give you an example. This pointer may also be supplied as a method argument. When working with events, passing this reference as a method parameter is typically necessary. For instance, if you wanted to start an event on the current object or handle, you would need to use this pointer to start it.

The programming example that follows shows how we gave this pointer to the method.

Example 1:

class Test_mtd
{
    int x;
    int y;
    Test_mtd ()
    {
x = 25;
y = 35;
    }
    void printV1(Test_mtd ob)
    {
             System.out.println("x = " + ob. x + " y = " + ob. y);
    }
    void get()
    {
           printV1(this);
    }
}
class Main{
    public static void main(String [] s)
    {
        Test_mtd obj = new Test_mtd ();
        obj.get();
    }
}

Output:

Value1 x = 25
Value2 y = 35

In this software, the main function creates an object of the class Test method, which is then passed to the get () method. The printV1 () method, which shows the current instance variables, receives the "this" pointer from the get () method.

Example 2:

class T_th {
    void print()
    {
        // calling funsho()
       this.show();
       System.out.println("T_th: print");
    }
    void sh() {
        System.out.println("T_th: sh");
    }
}
class Main{    
    public static void main(String s[]) {
        T_th t = new T_th();
        t.print();
    }
}

Output:

T_th: print
T_th: sh

When the class object in the main function calls the class method print (), it uses this pointer to call the display () method.

Return With ‘this’:

You can quickly return "this" reference if the method's return type is an object of the current class. In other words, a procedure that uses the "this" pointer can return the current object. The implementation for returning an object via the "this" pointer is provided below.

class T_th
{
   int avalue;
   int bvalue;
    //constructor of default
   T_th()
    {
        avalue = 10;
        bvalue = 20;
    }
   T_th get()
    {
        return th;
    }
   void disp()
    {
         System.out.println("avalue = " + avalue + “bvalue = " + bvalue);
    }
}
class Main{
    public static void main(String[] s)
    {
        T_th obje = new T_th();
obje.get ().disp ();
    }
}

Output:

 avalue = 10;
 bvalue = 20;

The program above demonstrates the method get (), which returns this, an object of the class Test this. The get () method then invokes the method display on the current object it returned.

3. this (): to invoke current class constructor:

The current class function Object () {[native code]} can be called using the this () function Object () {[native code]} call. It allows for the function Object () {[native code]} to be reused. In other words, function Object () {[native code]} chaining is accomplished using it. Additionally, you can call the function Object () {[native code]} of the current class using the "this" pointer. Reusing the function Object () {[native code]} is the core concept. Again, if your class has multiple constructors, you can call them all from one another in a process known as function Object () {[native code]} chaining.

Example 1:

class SA {  
SA () {System.out.println("hello raju");}  
SA(int t){  
Th();
System.out.println(t);
}  
}  
class TeTh5{  
public static void main(String s[]){  
SA y=new SA(110);
}}  

Output:

hello a
110

Calling parameterized constructor from default constructor:

Class RA{  
RA(){  
Th(55);
System.out.println("hello raju");
}  
RA(int n){  
System.out.println(n);
}  
}  
class TeTh6{  
public static void main(String s[]){  
RA ta=new RA();
}}  

Output:

55
hello raju

Example 2:

class Th_const
{
     int v11;
     int v12;
    Th_const()
    {   
Th(10, 20);
        System.out.println("Default constructor is ehnanced \n");
    }


    //Here Parameterized constructor is initiated
   Th_const(int v11, int v12)
    {
        this.v11 = v11;
        this.v12 = v12;
        System.out.println("the Parameterized constructor is declared");
    }
}
class Main{
    public static void main(String[] s)
    {
         Th_const obj = new Th_const();
    }
}

Output:

the Parameterized constructor is declared
Default constructor is enhanced

There are two constructors in the class in the program mentioned above. Using the 'this' pointer and the class's default function Object () {[native code]}, we call the other function Object() {[native code]}.

4. this: to pass as an argument in the method:

Additionally, you can give a function Object () {[native code]} the "this" pointer as an argument. This is more useful when you have numerous classes, as in the implementation that follows. The method also accepts this keyword as an input. It is primarily employed while handling events. Here's an illustration:

Example 1:

class SSR1 {  
  void Dee (SSR2 ob) {  
  System.out.println(“invoking the method");
  }  
  void pass (){  
Dee(this);
  }  
  public static void main(String s[]){  
  SSR1 s = new SSR1();
s. pass();
  }  
}  

Output:

Invoking the method

Use of this that is permissible as an argument:

When handling events or when we need to give another class a reference, for example. One object can be used in numerous ways thanks to it.

Example 2:

class SA sec
{
     SB sec bj;


     SA sec (SB sec bj)
    {
        this.bj = bj;
        bj.display();
    }
 }
class SB sec
{
    int a = 20;
    SB sec ()
    {
          SA sec bj = new SA sec(this);
    }
    void display()
    {
          System.out.println("B:a = " + a);
    }
}
class Main{
     public static void main(String[] s) {
        SB sec bj = new SB sec ();
    }
}

Output:

B:a = 20

We have two classes, as demonstrated in the implementation above, and each class's function Object () {[native code]} calls the function Object () {[native code]} of the other class. This is accomplished by using the "this" pointer.

5. this: to pass as argument in the constructor call:

This keyword can also be sent to the function Object () {[native code]}. If we need to use a single object across different classes, it is helpful. Here's an illustration:

Example 1:

class BA {  
  AA4 bj;
  BA (A4 bj){  
    this.bj=bj;
  }  
  void disp(){  
    System.out.println(bj. da) ;//using data member of A4 class  
  }  
}  
class AA4{  
  int da=10;
  AA4(){  
   BA ba=new BA(this);  
ba. display();
  }  
  public static void main (String s []) {
   AA4 aa=new A4();
  }  
}  

Output:

10

We have two classes, as demonstrated in the implementation above, and each class's function Object () {[native code]} calls the function Object () {[native code]} of the other class. This is accomplished by using the "this" pointer.

Example 2:

class ASS
{
	BSSbj;
	// A parameterized function Object () {[native code]} using a BSS object
	// as a parameter
	ASS (BSS obj)
	{
		this.bj = bj;
	//display method of class BSS is called
		bj. disp ();
	}
}
class BSS
{
	int a = 15;
	// Default Constructor that create a object of A
	BSS ()
	{
		ASS bj = new ASS(this);
	}
	
	// method to show value of a
	void disp ()
	{
		System.out.println("Value of a in Class BSS: " + a);
	}
	
	public static void main (String [] s) {
		BAA bj = new BAA ();
	}
}

Output:

Value of a in Class BSS: 5

6. this keyword can be used to return current class instance:

This keyword can be returned from the method as a statement. In this scenario, the method's return type is required to be a class type (non-primitive). Here's an illustration:

This is syntax, which may be used to return a statement:

Returndatatype methodname () {
return this;
}

Example 1:

class AA {  
AA getAA(){  
return this;
}  
void mg () {System.out.println("Hello javatpoint");}  
}  
class T1{  
public static void main(String s[]) {
new AA (). getAA ().mg ();
}  
}  

Output:

Hello javatpoint

Proving this keyword

How about we establish that this keyword corresponds to the current class instance variable? The result of both variables is same since we are printing the reference variable in this application.

class AA5{  
void mg (){  
System.out.println(this);
}  
public static void main(String s[]){  
AA5 bj=new AA5();
System.out.println(bj);//prints the reference ID  
obj.mg ();
}  
}  

Output:

AA22b3ea59
AA22b3ea59

Conclusion

The Java program's current object is indicated with the term "this." It can be used to eliminate misunderstanding brought on by class variables (also known as instance variables) and method arguments having the same names.

This pointer can be used in a variety of ways, such as to access instance variables, supply arguments to methods or constructors, return the object, etc. The Java language's crucial keyword "this" is a practical tool for gaining access to the current object's members and functions.


Related Topics

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 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.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.