Brian O'Shea wrote:If postfix increment has a higher precedence than prefix increment and both work right to left why is y equal to 134.
First, apply precedence -- and you get...
Note that it doesn't matter that postfix has higher precedence than prefix. And associativity is not needed.
To evaluate, you need to go left to right -- as defined by the specification. Normally, this is not a concern, but since prefix and postfix has side effects, you have to evaluate in the correct order. Also, since there are no short-circuiting operators being used, no need to deal with the added complexity. So...
Brian O'Shea wrote:That postfix is higher than prefix.
Does it really matter? Since it is not possible to apply both postfix and prefix at the same time, any difference in precedence is moot (as it is a syntax error). The precedence of postfix over the unary operators are more applied to the other unary operations (than the prefix operators).
Now, as for why the prefix operator has the same precedence as the unary operators -- I never really thought about it much. My guess is that it works better that way. Regardless, it is the same precedence of C/C++, which Java heavily borrowed from. Perhaps the Java designers didn't think about it much either ...
For post-increment and pre-increment I would just remember that pre-increment operators change the value before the expression is evaluated and post-increment changes it after.
So for instance given this code:
What is happening is java interprets this as: y = (11 * 11) + 13;
This is because 10 is first pre-incremented to 11 then because of precedence the multiplication part of the expression happens first. Now keep in mind that the post-increment on the second operand has not executed yet, it does this sometime before the last addition operator executes so 11 post-increments to 12 for instance then pre-increments to 13. And there you have it!
Check out this picture I made to help memorize java operator precedence.