多个运算符的Java优先级

这更多的是理解 Java对算术运算的评估的理论问题.由于和 – 具有相同的优先级,我不太明白Java如何评估以下表达式(两个操作数之间有多个操作符).
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
}

从Java 8语言规范(§15.8.2):

The binary + operator performs addition when applied to two operands of numeric type,producing the sum of the operands.
The binary – operator performs subtraction,producing the difference of two numeric operands.
[…]
Addition is a commutative operation if the operand expressions have no side effects.
Integer addition is associative when the operands are all of the same type.

我也注意到,每次#perators是偶数,结果是一样的,顺序并不重要.
但是当#operators是奇数时,这并不一定会影响结果.例如.在以下两个表达式中还有一个 – 但结果不同.

System.out.println(a-+-b);   // results in 3
System.out.println(a-+-+-b); // results in -1

有了所有这些信息,我仍然看不到这种模式或这种方式如何运作.

解决方法

在数学上,你怎么评价这个?
a - + - b

添加一些括号有助于:

a - (+ (-b))

我们可以这样做,因为这并不违反优先规则.

那么我们可以开始减少:(-b)真的是-b,而-b是真的是b,所以结果是1 2 = 3.

我们来看看第二个:

a - + - + - b
a - (+ (- (+ (-b))))
a - (+ (- (-b)))
a - (+ b)
a - b
1 - 2 = -1

这么简单的数学规则自然而然.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...