-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
  • 125,519
  • 44
  • 317
  • 399
Pradeep kumar
  • 125
  • 1
  • 7

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,806
  • 1
  • 23
  • 41
Suresh Atta
  • 118,038
  • 37
  • 189
  • 297