Reputation: 562
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?
Upvotes: 4
Views: 246
Reputation: 56489
The Pseudocode below shows how the expression is evaluated:
boolean t1 = false?false:true?false:true?false:true
= true && (true ? false : true ? false : true)
= true && false
= false
Another way to look at it:
boolean t1 = false?false:true?false:true?false:true;
can be simplified to:
boolean t1 = !false && (true ? false : true ? false : true);
then simplified to:
boolean t1 = true && (true ? false : true ? false : true);
then simplified to:
boolean t1 = true && false;
which eventually results in false
;
Upvotes: 1
Reputation: 403198
We can regroup these operations according to associativity rules.
boolean t1 = (false ? false : (true ? false : (true ? false : true)));
| | |
| | 1
| 2
3
In theory, this is what should happen
false
. true? false : false
so the final output is false
. false ? false : false
, which is false
.Now, to get technical, this is what actually happens:
false ? (don't care) : (...)
-> the inner expression containing Exp 2 and Exp 1 need to be evaluated.true: false, (don't care)
Since we've already determined the value of Exp 2, Exp 1 no longer needs to be evaluated.false ? (don't care) : false
and so the final answer is false
.Upvotes: 4
Reputation: 394146
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
.
Upvotes: 5