Please open the menu to show more

Friday, August 4, 2017

Frequently asked question asked by good companies on java programming language part-2

Here is a very very important question frequently asked in IT companies

=========================================

Question# => What is 'this' keyword in java. Why it is so important and how we use it.

Answer => 'this' is a reference variable which stores the address of current object. 
'this' keyword can be used inside non static methods and constructors only. 

if we use 'this' keyword inside static methods the compiler will report an error.
The most important benefit of 'this' keyword is to prevent the naming conflict of local and non static variables.

I mean, if the name of local variable and non-static-variable is same the 'this' reference-variable will always point to non static variables

for example =>

class Foo
{
// here 'x' is a non static variable
int x=100;
// it is a non static method
void fx()
{
// here 'x' is a local variable
// look here, the name of local and non static variable is same
int x=200;
// lets access a local variable
x++;
// lets access non static variable
this.x++;
}
// define main method
public static void main(String[] args)
{
// create object of class Foo
Foo f = new Foo();
// call the method fx() on object name 'f'
// since we are calling fx() method on 'f' the 'f' will be treated like 
// current object
f.fx();
}
}


2 comments: