• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

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

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

this.variablename


this. always represents global variables

class Demo
{
int x=10; // global variable
void show()
{
int x=20; // local variable
System.out.println(x); //local
System.out.println(this.x); //global
}
}
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 whith the help of single object creation.
1.without this() program
2.with this program

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");
}
}
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

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");
}
}
class Main
{
public static void main(String args[])
{
Demo d3=new Demo(10,20);
}
}


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