The book that I'm referring to on this post is: OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808 by Jeanne Boyarsky; Scott Selikoff.
I couldn't provide the page number as I'm using an electronic of the book. Under section Increment and Decrement Operators there is the following example along with the explanation provided.
int x = 3;
int y = ++x * 5 / x-- + --x;
System.out.println("x is " + x);
System.out.println("y is " + y);
This one is more complicated than the previous example because x is modified three times on the same line. Each time it is modified, as the expression moves from left to right, the value of x changes, with different values being assigned to the variable. As you'll recall from our discussion on operator precedence, order of operation plays an important part in evaluating this example.
So how do you read this code? First, the x is incremented and returned to the expression, which is multiplied by 5. We can simplify this:
int y = 4 * 5 / x-- + --x; // x assigned value of 4
Next, x is decremented, but the original value of 4 is used in the expression, leading to this:
int y = 4 * 5 / 4 + --x; // x assigned value of 3
The final assignment of x reduces the value to 2, and since this is a pre-increment operator, that value is returned to the expression:
int y = 4 * 5 / 4 + 2; // x assigned value of 2
Finally, we evaluate the multiple and division from left-to-right, and finish with the addition. The result is then printed:
x is 2
y is 7
According to table: 2.1 the post-unary operators have the highest precedence, why didn't we start with x-- first, but instead we proceeded from left to right as if the post-unary and pre-unary operators have the same precedence?
You are mixing up the order of evaluation with operator precedence. Operator precedence affects which operands go with which operators. Think of it as a two-pass process where operator precedence dictates putting explicit parentheses around operations that should be performed together before their results are used in other operations. Once the parentheses establish the grouping of operations, the operations are then evaluated from left to right and always from left to right.
First pass: put explicit parentheses around terms:
int y = (((++x) * 5) / (x--)) + (--x);
int y = (((4) * 5) / (x--)) + (--x);
int y = ((20) / (x--)) + (--x);
int y = (20 / 4) + (--x);
int y = (5) + (--x);
int y = 5 + 2;
int y = 7;
(x == 2)
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Thank you Junilu for taking the time to answer my question.
You are right I was confusing between the order of execution, which is always from left to right, and the operators perecendency, which determins with which operator operands go.