java如何让他们优先运算_多个运算符的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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值