在使用 Java 中的复合赋值运算符时,运算符的顺序是否重要?(+= vs =+)

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

Does order of operators matter when using compound assignment in Java? (+= vs =+)

问题

我有这段测试代码,我想要检查 sum =+ value 是否等同于 sum = sum + value。在Java中,这样写是可以的。它可以编译并且在我的机器上运行。

public class sum {
    public static void main(String[] args) {
        int sum = 0;
	    int value = 5;

        sum =+ value;
        System.out.println(sum);

        sum = 0;
        sum = sum + value;

        System.out.println(sum);
    }
}
英文:

I have this test code and I am trying to check if sum =+ value is equal to sum = sum + value. In Java, is this acceptable? It compiles and runs on my machine.

public class sum {
    public static void main(String[] args) {
        int sum = 0;
	    int value = 5;

        sum =+ value;
        System.out.println(sum);

        sum = 0;
        sum = sum + value;

        System.out.println(sum);
    }
}

答案1

得分: 2

是的,这很重要。

没有=+ 运算符。实际上它是两个运算符 - =(赋值),然后是 +(一元加法)。
sum =+ value 可以写成 sum = (+value),它只是等同于 sum = value

另一方面,+= 是一个适用于加法的正确运算符,sum += value 的意思是 sum = sum + value

英文:

Yes, it matters.

There is no =+ operator. It's, in fact, two operators - = (assignment), followed by + (unary plus).
sum =+ value could be written as sum = (+value), which just evaluates to sum = value.

On the other hand += is a proper operator using for addition sum += value means sum = sum + value.

huangapple
  • 本文由 发表于 2020年4月10日 07:13:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61131692.html
匿名

发表评论

匿名网友

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

确定