Search code examples
operator-keywordoperator-precedencepostfix-operatorprefix-operator

precedence operator in java 8 - postfix operator first


Following the precedence operator in java 8 it is clear that the postfix operator (expr++ expr--) has a higher precedence that the unary operator, pre-unary operator (++expr --expr). However when executing this code:

x = 3; y = ++x - x++;

The value of y is 0

But to me, following the above table, the result should be y = (5 - 3) as x++ should be evaluated first.

Can anyone explain why this is y = 0 and not y = 2?


Solution

  • When do I use the Operator precedence on the same line in an expression? or why there is an operator precedence order and when is used?

    Operator precedence decides which one of several operators is associated with an operand. In the expression ++x - x++ there are two places where precedence comes into play:

    1. ++x - … - The two operators ++ and (binary) - could be used on x; ++ has precedence, so this is equivalent to (++x) - …, not to ++(x - …).
    2. … - x++ - The two operators (binary) - and ++ could be used on x; ++ has precedence, so this is equivalent to … - (x++), not to (… - x)++.