What (in the specs) warrants that 'non short circuit logical operators will in fact not short circuit?

StackOverflow https://stackoverflow.com/questions/9266844

  •  29-04-2021
  •  | 
  •  

Question

This is directly inspired by this question.
There are numerous references/statements that bitwise operators, when applied to booleans, will not short circuit. So in other words boolean a = f() & g(), where f() and g() both return boolean, both always will be evaluated.
However, JLS says only:

15.22.2 Boolean Logical Operators &, ^, and |
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.

How this warrants that both operands are actually evaluated? Apart from xor, you are still able to break and return result if one of arguments (and it may be second/right being first to be evaluated) violates condition.
Eg. a & b would need only to evaluate b to be false to evaluate the expression to false.

Please note: I'm not asking if it is implemented this way (does not short circuit) -it certainly is.

I'm asking:

Would implementing it with short circuit violate language standard?

Was it helpful?

Solution

See JLS 15.7.2 Evaluate Operands before Operation

The Java programming language also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

So if you have the operator &, both operands need to be evaluated before the final result is computed.

Additionally, the section before that one explicitly requests that the left operand of any binary operator needs to be evaluated first.

OTHER TIPS

The JLS explicitly states that shortcutting is performed for conditional-or and the conditional-and. It explains the behavior of the conditional-or/and in terms of the bitwise-or/and operators. So, it is emphasizing that shortcutting is a variation in behavior from the bitwise operators.

So, I would say using shortcutting would violate the standard. It would definitely violate developers' expectations.

15.24 Conditional-Or Operator ||

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top