This Keyword in Java.

This keyword is a reference variable that refer to a current Object.

This can be used to refer current class instance variable.

If we don't use this keyword.

class Staff{

int idno;

String name;

long salary;

Staff(int idno,String name,long salary){

Idno = idno;

name = name;

salary = salary;

}

void display(){System.out.println(idno+" "+name+" "+salary);}

}

class Testing{

public static void main(String args[]){

Staff s1 = new Staff(111,"ankit",5000l);

Staff s2 = new Staff(112,"sumit",6000l);

s1.display();

s2.display();

}

}

Output:

0 null 0.00

0 null 0.00

In the above example, parameters (formal arguments) and instance variables are same.

Using this keyword

class Staff{

int idno;

String name;

long salary;

Staff(int idno,String name,long salary){

this.idno = idno;

this.name = name;

this.salary = salary;

}

void display(){System.out.println(idno+" "+name+" "+salary);}

}

class Testing2{

public static void main(String args[]){

Staff s1 = new Staff(111,"ankit",5000l);

Staff s2 = new Staff(112,"sumit",6000l);

s1.display();

s2.display();

}

}

Output:

111 ankit 5000.0

112 sumit 6000.0

This keyword used to invoke current class Method.

If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

Conclusion

The keyword ‘this’ is a reference to the current object in the Java program. It can be used to avoid confusion resulting from the same names for class variables (instance variables) and method parameters.

You can use ‘this’ pointer in many ways like accessing instance variables, passing arguments to method or constructor, returning the object, etc. The pointer ‘this’ is an important keyword in Java and is a helpful feature for accessing the current object and its members and functions.