英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论