Do &= and |= short-circuit in Java?

前端 未结 2 1230
没有蜡笔的小新
没有蜡笔的小新 2020-12-17 08:03

In other words, do the following two statements behave the same way?

isFoobared = isFoobared && methodWithSideEffects();
isFoobared &= methodWith         


        
2条回答
  •  清酒与你
    2020-12-17 08:17

    No, they do not, because x &= y is short for x = x & y and x |= y is short for x = x | y. Java has no &&= or ||= operators which would do what you want.

    The & and | operators (along with ~, ^, <<, >>, and >>>) are the bitwise operators. The expression x & y will, for any integral type, perform a bitwise and operation. Similarly, | performs a bitwise or. To perform a bitwise operation, each bit in the number is treated like a boolean, with 1 indicating true and 0 indicating false. Thus, 3 & 2 == 2, since 3 is 0...011 in binary and 2 is 0...010. Similarly, 3 | 2 == 3. Wikipedia has a good complete explanation of the different operators. Now, for a boolean, I think you can get away with using & and | as non-short-circuiting equivalents of && and ||, but I can't imagine why you'd want to anyway.

提交回复
热议问题