问题
Please have a look at the following code:
int i=5;
boolean b = i<5 && ++i<5;//line 2
System.out.println(i);//line 3, prints 5
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?
EDIT: 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
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?
回答1:
That's not how the expression is processed.
In Java, all expressions are evaluated from left to right. Operator precedence only comes into play when considering the evaluation of the arguments of &&
.
So i < 5
is computed before ++i < 5
is even considered.
In this case ++i < 5
will not be evaluated, since i < 5
is false
. So i
stays at 5
.
回答2:
The key is: ++ has the highest precedence inside a expression, but the sentence boolean b = i<5 && ++i<5
has two expressions evaluated from left to right.
Think of b = i<5 && ++i<5
like:
if( i<5 ){
if ( ++i<5 ){
return true;
}
}
回答3:
Considering your edited answer, the second code snippet also evaluates from left to right.
In both cases there is an expression of the form A && B
with A
as the left argument and B
as the right argument of &&
.
Here is where "left-to-right" applies. First, the left expression A
is evaluated. In your first code snippet, that is i<5
and since this expression evaluates to false
, the second argument to that isn't even considered, since the whole expression will evaluate to false
(short-circuiting).
In your second snippet you have as left argument a==b
. Since that evaluates to true
, only now the second argument is considered, which also evaluates to true
. That leaves you with true && true
which can then be processed further.
回答4:
Your misunderstanding is in how the '&&' works. When you use them java uses short circuit or lazy evaluation.
boolean equal = 1==1 && 1==2
java evaluates the 1==1
sees it as true
, checks the ampersands and has to evaluate the 1==2
which is false
and therefore equal
is false
.
boolean equal = 1==2 && 1==1
java evaluates the 1==2
sees it as false, then checks the ampersands and can see that whether the next expression is true or false the outcome is the same, that equal
is false
. Therefor it never evaluates the second equation.
More plainly the second example is saying boolean equal = false & true
. This can only be true if both are true. Thus knowing the first is false is all we need to know the outcome. By ignoring the sencond expression at this point we can save needless calculations.
来源:https://stackoverflow.com/questions/39852128/working-of-short-circuit-and-unary-operator