0

I have following code

class Demo {
    static int a = 0;
    static int b = 1;
    static {
        a = ++b;
    }

    void gam(int x) {
        a = a * x;
        b = b * x;
    }
}

class Test {
    public static void main(String[] args) {
        Demo d1 = new Demo();
        Demo d2 = new Demo();
        d1.a++;
        d2.a--;
        System.out.println(d1.a + " " + d1.b + " " + d2.a + " " + d2.b);
    }
}

But I can't figure out why d1.a is 2. Shouldn't it be 3? Since a=++b makes it 2 and d1.a++ makes it 3?

2 Answers 2

10

The variable a is static, so there is only one a for all instances of Demo. It starts off as 0, and the static initializer sets it to ++b, or 2. Then, d1.a++ increments it to 3, but d2.a-- decrements the same a back down to 2.

Sign up to request clarification or add additional context in comments.

Comments

0

d1.a is a static member field, so it should be accessed not via the instance. It should accessed via: Demo.a.

And by the way, d1.a and d2.a refer to the same static member field, so the increment of a in d1.a++ is "roll-backed" with the decrement: d2.a--.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.