class Demo {
public static void main(String args[]) {
A a = new A();
A b = a;
System.out.println(a.x);// 10 As expected
System.out.println(b.x);// 10 As expected
a.change();
System.out.println(a.x);// 10 WHY 10! still. Displays 20 if I remove int
// data type under change method.
System.out.println(b.x);// 10 WHY 10! still.Displays 20 if I remove int
// data type under change method.
}
}
class A {
int x = 10;
public void change() {
int x = 20; // I am delcaring this with int data type
}
}
Asked
Active
Viewed 89 times
-5

Tunaki
- 132,869
- 46
- 340
- 423

Pradeep kumar
- 145
- 1
- 8
-
1`int x = 20;` inside method, create a new local variable with name x. – Subhrajyoti Majumder Sep 03 '15 at 08:22
-
@SubhrajyotiMajumder `create a new local variable` ? That is actually causing the issue :) – Suresh Atta Sep 03 '15 at 08:23
-
indeed. As your answer already cleared tht fact. – Subhrajyoti Majumder Sep 03 '15 at 08:25
-
Read about [variables](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html) in java. – alex2410 Sep 03 '15 at 08:35
-
possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – merours Sep 03 '15 at 08:37
-
I got it as Creating local variable wil be inside the local scope to that method only, it wil not over ride the instance variable... – Pradeep kumar Sep 03 '15 at 12:14
1 Answers
2
In the method
public void change(){
int x=20; // I am declaring this with int data type
}
You are declaring a new variable which is not the variable x
at instance level.
Change your method to
public void change(){
this.x=20; // I am declaring this with int data type
}

Scott
- 1,863
- 2
- 24
- 43

Suresh Atta
- 120,458
- 37
- 198
- 307