Rules say the following for order of operations: 1. Parentheses 2. Exponents 3. Modulo/Multiplication/Division 4. Addition/Subtraction.
Stephan van Hulst wrote: 5 * 4 = 20
20 % 3 = 2
2 - 2 = 0
0 + 1 = 1
That was correct when you did your maths at school, but it isn't correct for Java®, which doesn't have an exponent operator. Not ^, which isn't an exponentiation operator at all. Joshua Bloch also says, Java® doesn't, strictly speaking, have a modulo operator; it has a remainder operator, which is slightly different. So your number 3 should read, “remainder/multiplication/division,” but that means those three operators all have the same precedence.Fredrik Andlin wrote:. . . order of operations: 1. Parentheses 2. Exponents 3. Modulo/Multiplication/Division 4. Addition/Subtraction. . . .
Yes, somebody has, and it's called the JLS (=Java®® Language Specification). It is in this sectionMaybe someone else will have a more clear explanation about that.
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, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
Your expression ends with xxx − 2 + 1; those two operators have the same precedence and associate to the left. Because those arithmetic operators associate to the left, the − is used before the +.A few minutes ago, I wrote:. . .
5: If two adjacent operators have the same precedence, which is used first depends on its direction of association. . . .
You had 4 % 3 - 2. That means the % is evaluated first. Had you written 4 - 3 % 2, the % would still be evaluated first.A few minutes ago, I wrote:. . .
4: If two adjacent operators have different precedences, that with the higher precedence is used first. . . .
Had you written 4 % (3 − 2), the − would be executed first.Earlier, I wrote:. . .
3: Expressions inside () are completed before the being used as an operand. . . .
That means, in an expression like 123 + myObject.getCount(), the method call completes before it is applied to the preceding + operator.In a previous post, I wrote:. . .
2: Operands are evaluated first. . . . .
This is the one that really causes confusion. Look at this old thread, and the link I quoted there. If you have something like:-The ++i is executed before the i-- because it is on the left.Not long ago, I wrote:. . .
1: And a partridge in a pear tree. . . .
Consider Paul's rocket mass heater. |