Search code examples
javaconditional-statementsconditional-operator

How are ternary expressions in Java evaluated?


I have followed the tutorial provided here and in the line:

boolean t1 = false?false:true?false:true?false:true;

the final value of t1 is false. But I've evaluated it as true. The first false gives true and that true gives false, which further finally gives true, am I right? No, I am wrong. Could you please tell me how ternary expressions are evaluated in Java?


Solution

  • When the compiler finds a ? character, it looks for a corresponding :. The expression before the ? is the first operand of the ternary conditional operator, which represents the condition.

    The expression between the ? and the : is the second operand of the operator, whose value is returned if the condition is true.

    The expression after the : is the third operand of the operator, whose value is returned if the condition is false.

    boolean t1 = false   ? false    :    true?false:true?false:true;
    
                 first     second        third
                 operand   operand       operand
    

    Since first operand is false, the result is the value of the third operand true?false:true?false:true, so let's evaluate it:

    true    ?   false    : true?false:true;
    
    first       second     third
    operand     operand    operand
    

    Since first operand is true, the result is the value of the second operand - false.

    BTW, the value of the third operand true?false:true is also false, so x?false:true?false:true returns false regardless of the value of x.