Tuesday, December 13, 2011

What is the use of this keyword in java?

'this' keyword can be used to differentiate the global variable and local variable.In the below example, first program is without using 'this' keyword and second program is using 'this' keyword.See the differences in the form of outputs.
Example:
class no_this
{
int a=10; //Here 'a'  is a  global variable
void take(int a)//Here 'a' is a local variable.within the function only it can be used
{
a=a;//here the local variable a is initialized itself.

}
void show()
{
System.out.println("a="+a); //here 'a' will print 10 only not 20
}
}
class test
{
public static void main(String args[])
{
no_this n=new no_this();
n.take(20);//it calls the take() method and assigns 20 to 'a'
n.show();
}
}
output:
a=10;

                 In the above example we are not using 'this' keyword so the local variable 'a' gets initialized itself.If we use 'this' keyword,we can easily differentiate the local and global variables.See the following example.
class with_this
{
int a=10; //Here 'a'  is a  global variable
void take(int a)//Here 'a' is a local variable.within the function only it can be used
{
this.a=a;//here the local variable 'a' is initialized to this.a(means global variable).
}
void show()
{
System.out.println("a="+a); //here 'a' will print 20
}
}
class test
{
public static void main(String args[])
{
with_this n=new with_this();
n.take(20);//it calls the take() method and assigns 20 to 'a'
n.show();
}
}
output:
a=20