Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are ternary expressions in Java evaluated?

I have followed the tutorial provide here and in line:

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

the final value of t1 is false. but i evaluated it as true. first false gives true and that true gives false which further finally gives true am i right? no i am wrong . please tell me how ternary expression are evaluated in java?

like image 315
Bibek Ghimire Avatar asked Dec 24 '22 17:12

Bibek Ghimire


1 Answers

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.

like image 175
Eran Avatar answered Jan 10 '23 21:01

Eran