Java priority of multiple operators
This is more a theoretical problem to understand Java's evaluation of arithmetic operations Since and – have the same priority, I don't quite understand how Java evaluates the following expression (there are multiple operators between two operands)
public static void main(String[] args) { int a = 1; int b = 2; System.out.println(a+-b); // results in -1 System.out.println(a-+b); // results in -1 System.out.println(a+-+b); // results in -1 System.out.println(a-+-b); // results in 3 System.out.println(a-+-+b); // results in 3 System.out.println(a+-+-b); // results in 3 System.out.println(a-+-+-b); // results in -1 System.out.println(a+-+-+b); // results in 3 }
From the Java 8 Language Specification (§ 15.8.2):
I also noticed that every time #perators are even, the result is the same, and the order is not important However, when #operators are odd, this does not necessarily affect the results For example There is also one of the following two expressions – but the result is different
System.out.println(a-+-b); // results in 3 System.out.println(a-+-+-b); // results in -1
With all this information, I still can't see this model or how it works
Solution
How do you evaluate this mathematically?
a - + - b
Adding some parentheses helps:
a - (+ (-b))
We can do this because it does not violate the priority rule
Then we can start to reduce: (- b) is really - B, and - B is really b, so the result is 1, 2 = 3
Let's look at the second:
a - + - + - b a - (+ (- (+ (-b)))) a - (+ (- (-b))) a - (+ b) a - b 1 - 2 = -1
Such a simple mathematical rule is natural