Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

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

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

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

I realize I could just write up a test, but someone might know this offhand, and others might find the answer useful.

question from:https://stackoverflow.com/questions/3152208/do-and-short-circuit-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, |= and &= do not shortcircuit, because they are the compound assignment version of & and |, which do not shortcircuit.

JLS 15.26.2 Compound Assignment Operators

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

Thus, assuming boolean &, the equivalence for isFoobared &= methodWithSideEffects() is:

isFoobared = isFoobared & methodWithSideEffects(); // no shortcircuit

On the other hand && and || do shortcircuit, but inexplicably Java does not have compound assignment version for them. That is, Java has neither &&= nor ||=.

See also


What is this shortcircuiting business anyway?

The difference between the boolean logical operators (& and |) compared to their boolean conditional counterparts (&& and ||) is that the former do not "shortcircuit"; the latter do. That is, assuming no exception etc:

  • & and | always evaluate both operands
  • && and || evaluate the right operand conditionally; the right operand is evaluated only if its value could affect the result of the binary operation. That means that the right operand is NOT evaluated when:
    • The left operand of && evaluates to false
      • (because no matter what the right operand evaluates to, the entire expression is false)
    • The left operand of || evaluates to true
      • (because no matter what the right operand evaluates to, the entire expression is true)

References


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...