Why is a Java ternary “graded” before or?

I have the following Java code snippet that returns false when I expect it to return true:

assertTrue(true || false ? false : false); 

The statement was discarded for the sake of this message (it was originally used to compare strings), and I know that it can be simplified so as not to use the ternary operator, but basically I'm trying to understand why Java evaluates it like this:

 (true || false) ? false : false 

instead of this:

 true || (false ? false : false) 

I expect him to evaluate the truth and come out. Does anyone know why this is not so?

+4
source share
4 answers

Because what the language specification says. Matching Grammar Bits

 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 A || B ? C : D A || B ? C : D ? C : D ? C : D must be Expression1Rest , and the right side || there must be Expression3 , which does not include a three-digit conditional expression (if it is not wrapped in parentheses - the expression in parentheses is always acceptable as Expression3 ). Therefore, we must analyze A || B A || B like Expression3 , and thus the whole expression, as if it (A || B) ? C : D (A || B) ? C : D

+5
source

Due to operator priority . Logical AND and Logical OR have a higher priority than the ternary operator, so they act first.

+15
source

Because || has a higher priority than ?: . Here is the statement table in Java . || has position 13, and ?: is in position 14.

+11
source

So, there is something called the operator’s priority . "This is the same concept as the order of work in mathematics. And just like in mathematics + appears after * , in Java ?: Appears after || .

Why is this so? Well, I think this helps to see the triple language as an extension to the if :

 true || false? false: false; // literally maps to if(true || false) false; else true; 
+2
source

Source: https://habr.com/ru/post/1490485/


All Articles