I was going through the 'Operators' chapter & topic - "Operator Precedence" of OCAJSE8 Book & encountered the below confusion:
I believe it's mentioned in the book as below:
When two operators of the same precedence are in the same expression, Java evaluates the expression from left to right
When parentheses are nested, the innermost parentheses are evaluated first
In the Precedence Hierarchy table, it's mentioned as: Short-circuit (&& beats ||)
Doubt: When only "Short-circuit Logical Operators" are present in an expression, which of the below two could be correct?
a. Evaluate all "&&" operators with it's left/right operand. (this I was thinking initially would happen)
b. Evaluate the expression from left-to-right. (this is observed presently)
1. Shouldn't the assignments happen in the below code first, as it's within the parenthesis and then expression evaluation?
2. And during expression evaluation, shouldn't "&&" be evaluated first?
3. If the evaluation is followed immediately after the assignment, then what does the quote "Short-circuit (&& beats ||) mean?
The output I was expecting, as per my present understanding:
all same except below
Evaluation order and operator precedence are two completely separate concerns that many programmers confuse with each other.
Operator precedence only determines which operands belong to which operators. Resolving operator precedence is a compile-time step that you can picture as the compiler inserting explicit parentheses everywhere. For instance, your statement:
Is equivalent to:Note the extra parentheses around the operands that belong to the && operator. This is because && has higher precedence than ||.
After this is done, operator precedence no longer plays any role at all.
At runtime, expressions are ALWAYS evaluated left-to-right. That means (a=true) is evaluated before ((b=true) && (c=true)). After (a = true) has been evaluated, the || operator sees that no matter what value of the right hand side evaluates to, the final result will always be true, so it short circuits.