问题描述
请查看以下代码:
int i=5;
boolean b = i<5 && ++i<5;//line 2
System.out.println(i);//line 3, prints 5
根据我的理解,在第2行中:由于在所有运算符中,++的优先级最高,因此应首先评估++i
.但是line 3
实际上正在打印i=5
(而不是6
).含义&&在++运算符之前进行了评估.这怎么可能?
In line 2, according to my understanding: Since among all the operators, ++ has highest precedence ++i
should be evaluated first. But line 3
actually is printing i=5
(and not 6
). Meaning, && has evaluated before ++ operator. How is it possible?
从答案中我看到在Java中,所有表达式都是从左到右求值的.". 但是实际上优先顺序何时生效.在以下代码中:
From the answers I see that "In Java, all expressions are evaluated from left to right.". But when does actually precedence order comes into play. In following code:
int a=1,b=1,c=1;
boolean b = a==b&&b==c;//Line2
在第2行中,代码不会只是从左到右运行.首先评估a == b,然后评估b == c,然后评估&&.操作员.你能解释更多吗?
In line2 code would't just run from left to right. First a==b is evaluated then b==c and then && operator. Can you please explain more?
推荐答案
那不是表达式的处理方式.
That's not how the expression is processed.
在Java中,所有表达式从左到右求值.仅当考虑对&&
的自变量进行评估时,运算符优先级才起作用.
In Java, all expressions are evaluated from left to right. Operator precedence only comes into play when considering the evaluation of the arguments of &&
.
所以i < 5
是在甚至没有考虑++i < 5
的情况下计算的.
So i < 5
is computed before ++i < 5
is even considered.
在这种情况下,将不评估++i < 5
,因为i < 5
是false
.所以i
停留在5
.
In this case ++i < 5
will not be evaluated, since i < 5
is false
. So i
stays at 5
.
这篇关于短路和一元运算符的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!