ilkay Polat wrote:But according to order of operation in Java, it should evaluate x-- firstly. Right?
No. Evaluation of expressions always proceeds from left to right.
If you want the gory details (and you probably should if you're writing a certification exam), here's a version of the language specification: Expressions. The part about evaluation order is section 15.7.
Where it says:
The JLS wrote:The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
This is what you need to know. It also says:
JLS wrote:It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation...
Which you'll notice, the example you're discussing seriously violates (on purpose) this recommendation.
As Paul has explained, the book is correct. Please search; this example has come up many times in this forum and it has confused just about everybody who read it.
It is not a case of “probably” wanting the gory details for the exam, but a case of definitely wanting the gory details. Be sure to look up the link Paul gave you.
ilkay Polat wrote:By choosing which operation to perform first, we are actually choosing between two different expressions:
1. (4 + 3) * 5 == 35
2. 4 + (3 * 5) == 19
In this case * has more priority than + in Java so second option is valid. So not always from left to right.
Indeed, this is all correct -- except for the last statement. Well, the last statement is correct if you're talking about the order in which the operators are applied, but that isn't the order in which the operands are evaluated. If you replace 4, 3, and 5 by expressions which have side effects (like printing their values on the console) then you'll see that 4 is evaluated first, then 3, then 5.
Read Marco's most recent post for an excellent description of how the expression in the exam works.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop