0

To get right to the point: When is it better to use single & or single | as opposed to their short-circuit && and || variants?

I can't seem to find an example where it would be better to evaluate both sides of a boolean expression.

Raizento
  • 13
  • 3
  • 4
    & and | are bitwise, not logical operators. You use them when working with numbers, not boolean values. – yole Jan 23 '19 at 18:36
  • 2
    @yole [The operators `&` and `|` also work with boolean values](https://docs.oracle.com/javase/specs/jls/se10/html/jls-15.html#jls-15.22.2). – rgettman Jan 23 '19 at 18:37
  • 1
    Interesting to see that 3 people upvoted @yole's incorrect comment... – Mark Rotteveel Jan 23 '19 at 18:42
  • The operators do work with boolean values, but you don't normally use them when working with booleans. I don't see why my comment is incorrect. – yole Jan 23 '19 at 18:48
  • 2
    @yole Because `|` and `&` are not (integer) bitwise operators in the context of booleans, they are non-shortcircuiting boolean logical operators, see the [Java Language Specification section 15.22.2](https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.22.2). True, you should not usually have need to use them, but that doesn't make your assertion true that _"[y]ou use them when working with numbers, not boolean values"_ – Mark Rotteveel Jan 23 '19 at 19:02

1 Answers1

0

As you have implied, you realize the difference between the short-circuit operators && and ||, and the non-short-circuit operators & and |. But when would the difference become significant? When the second expression has a side effect or is a long-running operation that impacts performance. The easiest example of a side effect would be a method call that happens to return a boolean, e.g.:

if (firstOperation() & secondOperation()) //...

When you need to ensure that the side effects take place, then don't short-circuit. But I don't see it in practice often, because it's clearer to call the methods with side effects first, then evaluate the condition, e.g.:

boolean first = firstOperation();
boolean second = secondOperation();

if (first && second) //...

Usually you will see the short-circuiting operators, which avoid evaluating the second operand if unnecessary. This comes in handy when the second condition has no side effects, and it can become important if the second condition involves a large overhead cost.

rgettman
  • 176,041
  • 30
  • 275
  • 357