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

this keyword, Variable Hiding in java

👁 2,015 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 Instance variable :" + this.variable);
  System.out.println("Value of Local variable :" + variable);
  }

  void method() {
  int variable = 50;
  System.out.println("Value of Instance variable :" + this.variable);
  System.out.println("Value of Local 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 Instance variable :5
Value of Local variable :20
Value of Instance variable :5
Value of Local variable :50
Press any key to continue . . .
                            
📚 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.