Increment and decrements static variable not showing updated value

Viewed 968

I was studying the use of static keyword and found that if a variable is created as static then one copy of it is created and shared among all the objects of the class.

But the output of below code confused me that why it is not showing incremented value.

public class Test {

    static int y = 10;

    public static void main(String[] args) {

        System.out.println(y);
        System.out.println(y+1);
        System.out.println(++y);
        System.out.println(y--);
    }

}

I was expecting the output to be:

10
11
12
12

But the actual output is:

10
11
11
11

Please help me to understand the output.

2 Answers

Let's go over the print statements to see what happens:

System.out.println(y);    // value of y is 10 -> print 10
System.out.println(y+1);  // value of y is still 10, but we print 10 + 1 -> print 11
System.out.println(++y);  // value of y becomes 11 before we print -> print 11
System.out.println(y--);  // value of y becomes 10 after we print -> print 11

The question has little to do with static variables. y could be a local variable, the behavior will be all the same.

To understand the 3rd and the 4th statement, read up on prefix operator and postfix operator.

The actual output is correct

Y+1 doesn't alter the value of variable y. So y will be 10 only. When you do ++y , it alter the value to 11.

Related