Search code examples
javastaticstatic-methods

Static Method accessing Static variable


public class Practice {
    int x;
    static int y;

    void functionA() {
        int y = 0;
        System.out.println("inside non static method functionA()");
        x = 10;
        y = 30;
        System.out.println(x);//10
        System.out.println(y);//30
        functionZ();
        System.out.println(x);//10
        System.out.println(y);//30

    }

    static void functionZ() {
        System.out.println("inside static method functionZ()");
        System.out.println("y: " + y);//prints 0, thought it was supposed to be 30?
    }

    public static void main(String[] args) {

        Practice s = new Practice();
        s.functionA();
    }


}

Can someone explain why upon execution, inside functionZ(), y is printed as 0 and not 30? Before z is invoked, in functionA we've already set the value to 30. And since there is supposed to only be one copy of a static variable across all instances of an object, shouldn't it be 30?


Solution

  • Inside your functionA you defining a local variable y:

    void functionA() {
        int y = 0;
        ...
    

    While you are in that function all access to y will go into this variable, so you set it to 30. This did however not impact the static variable y, which still has the value 0 and it is accessed from the static method functionZ.

    To emphasize you want to access the static variable y rather than the local variable y, use the qualified identifier Practice.y.