微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多个运算符的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

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

原文地址:https://www.jb51.cc/java/123213.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐