什么是Java运算符的正确顺序?

huangapple go评论55阅读模式
英文:

What the right order of Java operators?

问题

我正在学习Java,并且刚刚了解到操作的执行顺序是由表达式中每个运算符的优先级确定的。

根据上面的图片,++和--首先被计算,但例如:

public class StudyDemo {
    public static void main(String[] args) {
        int a = 5;
        int result = -a++;
        System.out.println(result);
    }
}

为什么结果的输出是 -5

英文:

I am learning Java and just learned that the order in which the operations are carried out is determined by the precedence of each operator in the expression.
什么是Java运算符的正确顺序?

According to the picture above, the ++ and -- are evaluated first, but for example:

public class StudyDemo {
    public static void main(String[] args) {
        int a = 5;
        int result = -a++;
        System.out.println(result);
    }

}

Why the result's output is -5?

答案1

得分: 1

a++后置递增操作。这意味着该值首先被读取为5,然后在此之后被递增(a++ 评估5,但作为副作用,它立即递增为6)。

因此,在表达式内部,a++评估为5,之后为6

使用一元减号-5变为-5

这与前置递增 ++a 相对,其中a首先递增为6,然后再被读取。

英文:

a++ is a post-increment. Which means the value is first read as 5 and then incremented afterwards (a++ evaluates to 5, but as a side effect, it is incremented to 6 immediately afterwards).

So a++ evaluates to 5 inside the expression and is 6 afterwards.

Using a unitary - turns 5 into -5.

This is in contrast to the pre-increment ++a, where a is incremented first to 6, and then read.

答案2

得分: 0

1) ++具有最高优先级,因此首先执行a++;但它是后增量,此处返回5
2) 现在符号操作符将负号添加到5
英文:
int result = -a++;
  1. ++ Has highest priority so a++ happens first; But it is post increment it returns 5 here
  2. Now the Sign Operator add negative sign to 5

huangapple
  • 本文由 发表于 2020年9月30日 16:19:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64133599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定