it prints out "31041"; in other words, it evaluates the second operand of the multiply and increments <index> before it evaluates the second operand of the addition, so 31 gets multiplied by 1000 before 41 gets added to the product.
Does Java define the expression above to act that way, or is the order the operands get evaluated undefined? I mean, if I wanted to be really sure the second operand of the multiplication gets evaluated before the second operand of the addition does, I could write:
My question is, if I really want to be absolutely sure of the order the two operands get evaluated, do I have to write it like I do with class <Ou>, or is writing it like I do with class <Om> enough?
Kevin Simonson wrote:
Does Java define the expression above to act that way
Yes. Unlike C/C++, this order is strictly defined in Java. We know that it will happen in the following order (leaving out some intermediate steps):
1. Evaluate 1000.
2. Evaluate index as 0.
3. Increment index to 1.
4. Use the before-incrementing value of index (0) from #2 as the value of the expression index++.
5. Use the 0 result of #4 as the index into the array.
6. Get the value 31 from index 0 at the array.
7. Multiply 1000 * 31.
... and so on.
Kevin Simonson wrote:My question is, if I really want to be absolutely sure of the order the two operands get evaluated, do I have to write it like I do with class <Ou>, or is writing it like I do with class <Om> enough?
Note that if you had actually wanted the addition to be done before the multiplication (i.e. you wanted the answer 72000), you wouldn't need to split the code into multiple lines. Brackets would have the same effect.
In fact, if I was writing your code I would have written it asThat way, when someone else comes along and looks at your code, they know for sure that you intended the multiplication to be done before the addition.
Judicious use of brackets also means that you don't have to worry about remembering which operators have precedence.