Why &= operator doesn't work the same as &&
I'm just curious how java works. Can someone explain why getBoolean
is called in Case 1 and not called in Case 2?
public class Main {
public static void main(String[] args) {
System.out.println("---------- Case 1 ----------");
boolean b = false;
b &= getBoolean(true);
System.out.println("---------- Case 2 ----------");
b = false;
b = b && getBoolean(true);
}
private static boolean getBoolean(boolean bool) {
System.out.println("getBoolean(" + bool + ") was calledn");
return bool;
}
}
Output:
---------- Case 1 ----------
getBoolean(true) was called
---------- Case 2 ----------
b &= a
is a shortcut to b = b & a
not to b = b && a
It is because of the difference between &
and &&
operators.
The &
operator always evaluates both sides of conditions.
The &&
operator evaluates the second only if needed.
So, getBoolean(true)
will not run in the 2nd case.
In Case 2 getBoolean(true);
is not evaluated, because the &&
is a short-circuit operator, eg if the expression will be false
it stops evaluating
Case 1 just sets the result of the getBoolean()
method to the b
variable.
Update, thanks to @KisHan:
Note that b &= a
is equal to b = b & a
and not b = b && a
In second case b
is false
and for &&
if first condition is false it won't move ahead.
b = b && getBoolean(true);//b is false
So &&
(Logical AND) first checks the left side of the operation, if it's true
than it continues
to the right side.
While &
(Bitwise AND) operator evaluates both sides of expression as it's bitwise AND operator.As it performs AND operation between leftside and right side.
So in first case it will be
b = b & getBoolean(true);//will perform AND operation to evaluate Expression
链接地址: http://www.djcxy.com/p/73918.html
上一篇: 额外的存储合并排序
下一篇: 为什么&=操作符与&&不一样