-1

// Here is the code for static variable....

class IdentifyMyParts {
    public static int x = 7;
    public int y = 3;
}

public class Testing {
    public static void main(String[] args) {
        IdentifyMyParts a = new IdentifyMyParts();
        IdentifyMyParts b = new IdentifyMyParts();
        a.y = 5;
        b.y = 6;
        a.x = 1;
        b.x = 2;
        System.out.println("a.y = " + a.y);
        System.out.println("b.y = " + b.y);
        System.out.println("a.x = " + a.x);
        System.out.println("b.x = " + b.x);
    }
} 
// Output:-             
a.y = 5               
b.y = 6                  
a.x = 2                    
b.x = 2             

Why the value of a.x is not changing? Why is it showing a.x = 2?

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
  • 1
    It *has* changed. `a.x` and `b.x` are the same, and when you do `b.x = 2`, you also set `a.x`. They both refer to `IdentifyMyParts.x`, and I really wouldn't suggest accessing static fields like they're instance variables – user Jun 23 '20 at 17:59
  • 1
    If you add a line to print `a.x` between the 2 lines `a.x = 1;` and `b.x = 2;` you will see `a.x` has changed. – 001 Jun 23 '20 at 18:01

1 Answers1

1

Static field is shared by all instances of the class. That field belongs to the class, not to a particular instance. Ie a.x and b.x point to same a place. BTW I guess even IDE warns you that you should use class identifier, not instance ie IdentifyMyParts.x and not a.x

Lonestar
  • 51
  • 6