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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With