• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

'this' keyword In Java

Java this keyword

this Keyword:
'this' is a keyword in java language which is used used in two different ways
1. this.
2. this( )

MSK TechnologiesTrainings

this.
this. is used to differentiate the local variables and global variables whenever both are same name.
Syntax:
this.variableName

Note : this. always represents global variable
class Demo
{
    int x=10; // global variable
    void show() 
    {
        int x=20;  // local variable
        System.out.println(x); //local variable
        System.out.println(this.x); //global variable
    }
}
public class Main
{
    public static void main(String args[])
    {
        Demo d=new Demo();
        d.show();
    }
}
                                

Output:
20
10
this( )
' this( ) ' it is used call the multiple constructors with the help of single object creation.
1.without this() program
2.with this program

Syntax :
class Claassname
{
    Claassname()
    {
    this(value1);
    Statement 1;
    Statement 2;
    ..
    ..
    }
    Claassname(Datatype Varable1)
    {
    this(value1,value2);
    Statement 3;
    Statement 4;
    ..
    ..
    }
    Claassname(Datatype Varable1,Datatype Varable2)
    {
    Statement 5;
    Statement 6;
    ..
    ..
    }
    ..
    ..

}
public class Main
{
    public static void main(String args[])
    {
        Claassname c1=new Claassname();     
    }
}
Note:
    this() always first statement of the every constructor.
without this( ) program
class Demo
{
    Demo( )
    {
        System.out.println("This is NOPC");
    }
    Demo(int x)
    {
        System.out.println("This is 1PC");
    }
    Demo(int x,int y)
    {
        System.out.println("This is 2PC");
    }
}
public class Main
{
    public static void main(String args[])
    {
        Demo d1=new Demo();
        Demo d2=new Demo(10);
        Demo d3=new Demo(10,20);
    }
}

                                

Output:
This is NOPC
This is 1PC
This is 2PC
with this program
with this( ) program
 
class Demo
{
    Demo( )
    {
        this(10);
        System.out.println("This is NOPC");
    }
    Demo(int x)
    {
        System.out.println("This is 1PC");
    }
    Demo(int x,int y)
    {
        this();
        System.out.println("This is 2PC");
    }
}
public class Main
{
    public static void main(String args[])
    {
        Demo d3=new Demo(10,20);
    }
}

                                

Output:
This is 1PC
This is NOPC
This is 2PC