this Keyword in Java

  • this holds the reference of current object. Observe below
    example:

class demo
{
                int  x=10;
                void show(int x,demo d1)
                {
                                System.out.println(this.x);
                                System.out.println(d1.x);
                                System.out.println(x);
                }
                public static void
main(String…s)
                {
                                demo d1=new
demo();
                                d1.show(20,d1);
                }
}

Output:

10
10
20
  • In Java by default this is passed to all non static methods.
  • this cannot be used into static methods.
  • this is the reference variable or local variable, it goes to
    stack.
  • When local and global variables are same then this situation
    is known as data shadowing. In such situation this keyword is used to
    distinguish between local and global variable.

Consider below example:
class demo
{
                int x=10;
                void show()
                {
                                int x=20;
                                System.out.println(this.x);           //golabal variable
                                System.out.println(x);                   //local variable, priority goes to local variable
                }             
                public static void
main(String…s)
                {
                                demo d=new
demo();
                                d.show();
                }
}

Output

10
20

Watch below video tutorial to understand this keyword easily

Leave a Reply

Your email address will not be published. Required fields are marked *