-5
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
    }

}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Pradeep kumar
  • 145
  • 1
  • 8

1 Answers1

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