Why does == have higher precedence than postfix ++ in Java?

Viewed 222

Please, could someone help me to figure out why equality has higher priority before postfix here?

int x = 6;
System.out.println(7 == x++);

Output: false

According to some sources of precedence of operators in Java: postfix should have higher priority than equality operator. In those sources there is also mentioned associativity of operators (but it should come in when the precedence level of operators in expressions are same).

2 Answers

If the precedence of equality were higher than that of the postfix increment, then 7 == x++ would be parsed as tbough written (7 == x)++. That's certainly not what is happening, since ++ cannot be applied to a boolean value, which is what 7 == x would produce. Nor can it be applied to an expression which is not a variable. So it is certainly the case that the expression is parsed as though written 7 == (x++); the postfix operator has higher precedence.

What's confusing you is that the result of the comparison is false, but that is to be expected. It's too be expected because the value of a postfix increment (x++) is the value of the variable before it was incremented. x is certainly being incremented, and it is incremented before the equality comparison is performed, but the comparison is not between 7 and the value of x. It's between 7 and the value returned by x++, which is 6 (the old value of x).

If you had written 7 == ++x, using the prefix increment operator, then it would have worked as you expected because the prefix increment operator returns the new value of the variable. That's why we have two different increment operators: sometimes you want to use the old value (postfix operator) and sometimes you want to use the new value (prefix operator).

As the name postincrement suggests, the increment happens after assignment. Thus, 7 == ++x is evaluated as

7 == x
x = x + 1

In contrast, with preincrement, 7 == ++x is evaluated as

x = x + 1
7 == x

Demo:

public class Main {
    public static void main(String[] args) {
        int x = 6;
        System.out.println(7 == ++x);
    }
}

Output:

true
Related