This keyword in Java

This keyword in Java

"this" keyword is the reference variable that refers to the current object

Consider the code below:

class Test
{
    int i;
    void setValue(int x)
    {
        i=x;
    }
    void show()
    {
        System.out.println(i);
    }
}
class Xyz
{
    public static void main(String[] args)
    {
        Test t=new Test();
        t.setValue(10);
        t.show();
    }
}

Output for the above code is 10. But when we consider the arguments and instance variables as the same variable then the output is "0".

class Test
{
    int i;
    void setValue(int i)
    {
        i=i;
    }
    void show()
    {
        System.out.println(i);
    }
}
class Xyz
{
    public static void main(String[] args)
    {
        Test t=new Test();
        t.setValue(10);
        t.show();
    }
}

We can overcome this by using this keyword

class Test
{
    int i;
    void setValue(int i)
    {
       this.i=i;
    }
    void show()
    {
        System.out.println(i);
    }
}
class Xyz
{
    public static void main(String[] args)
    {
        Test t=new Test();
        t.setValue(10);
        t.show();
    }
}

Uses of "this" keyword

  • this keyword can be used to refer current class instance variable.

  • this keyword can be used to invoke the current class method implicitly

  • this() can be used to invoke the current class constructor.

  • this can be used to pass as an argument in the method call.

  • this can be used to pass as an argument in the constructor call.

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