Home / Programs / Variable Hiding in java, intro for this keyword
🚀 Programming Example

Variable Hiding in java, intro for this keyword

👁 1,470 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

💻 Program Code

 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.

*/
                        

🖥 Program Output

Value of variable :20
Value of variable :50
Press any key to continue . . .
                            

📘 Explanation

As you can see in the example above the instance variable is hiding and the value of the local variable(or Method Parameter is displayed not instance variable. To solve this problem use this keyword with a field to point to the instance variable instead of the local variable.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.