1

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?

3
  • 1
    Operator precedence does not determine the order of evaluation. Commented Aug 29, 2021 at 7:23
  • I saw this link about What are the rules for evaluation order in Java? Well, there is an explanation but still is not 100 % clear. Let me ask the question in a different way: 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? Commented Aug 30, 2021 at 9:43
  • postfix-notation has nothing to do with it. Commented Oct 7, 2021 at 11:08

1 Answer 1

0

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)++.
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks @Armali for your response and time. That is understandable, but then I am back to x = 3; y = ++x - x++; Why on this expression x++ has not precedence over '-' operator? That is what I cannot understand
I mean x++ has not precedence over '-' operator, so then x++ is evaluated before --x
I'm sorry, those phrases don't make sense: (a) x++ has not precedence - A term as x++ cannot have precedence, only an operator as ++ can. (b) x++ is evaluated before --x - There is no --x in the example.
We agree where you ask "Do we agree". But in this where we agree, there is no logic at all which would say anything about the order of evaluation. What's more, in your example there is no precedence relation between the two increment operators, because they cannot be associated to the same operand - precedence between the two could only exist in an expression like ++x++. // You cannot tell the order of evaluation just from a precedence table.
Many thanks @Armali, I will digest it bit by bit :)
|

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.