Why is a Java ternary "evaluated" before an or?

java

Solution

Because that's what the language specification says. The relevant bits of the grammar are

Expression: 
     Expression1 [AssignmentOperator Expression1]

Expression1: 
     Expression2 [Expression1Rest]

Expression1Rest: 
     ? Expression : Expression1

Expression2:
     Expression3 [Expression2Rest]

Expression2Rest:
     { InfixOp Expression3 }
     instanceof Type


InfixOp: 
     || 
     &&
     // and many other operators

So to parse `A || B ? C : D`, the `? C : D` must be an `Expression1Rest`, and the right hand side of a `||` must be an `Expression3`, which does not include a ternary conditional expression (unless it is wrapped in parentheses - a parenthesized expression is always acceptable as an `Expression3`). So we must parse the `A || B` as an `Expression3`, and thus the whole expression as if it were `(A || B) ? C : D`.

Problem

I have the following Java code snippet that is returning false when I would expect it to return true: ``` assertTrue(true || false ? false : false); ``` The statement has been dumbed down for the sake of this post (it was originally using string comparisons), and I know it can be simplified to not use the ternary operator, but basically I'm trying to figure out why Java evaluates it like this: ``` (true || false) ? false : false ``` rather than this: ``` true || (false ? false : false) ``` I would expect it to evaluate the true and exit. Does anyone know why it doesn't?

Original source