class VariableHiding {
int variable = 5;
void method(int variable) {
variable = 20;
System.out.println("Value of variable :" + variable);
}
void method() {
int variable = 50;
System.out.println("Value of variable :" + variable);
}
public static void main(String args[]) {
VariableHiding obj = new VariableHiding();
obj.method(20);
obj.method();
}
}
/*
this keyword can be very useful in the handling of Variable Hiding.
We can not create two instance/local variables with the same name.
However it is legal to create one instance variable & one local variable
or Method parameter with the same name. In this scenario the
local variable will hide the instance variable this is called Variable Hiding.
*/
Value of variable :20
Value of variable :50
Press any key to continue . . .
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.