英文:
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.
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++;
- ++ Has highest priority so a++ happens first; But it is post increment it returns 5 here
- Now the Sign Operator add negative sign to 5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论