# Ternary Operator

ali bergen
Greenhorn
Posts: 5

Hi everybody,

Here is a question from ternary operator section.

public class Test {
public static void main(String... parans) {
System.out.println(true?false?"7":false?"6":false?true?"5": true?"4":"3":"2":"1");
}
}

Could anybody explain why the output is 2.
Thanks

Henry Wong
author
Marshal
Posts: 21518
84
• 2
First step is to clean up the expression -- add parens to represents precedence.

Once, you do that, then it's easy....

Just follow the first branch for true, and the second branch for false.

Henry

ali bergen
Greenhorn
Posts: 5
Thanks a lot Henry for quick reply.

Still I dont understand, could please explain little more.

Thanks!

Hunter McMillen
Ranch Hand
Posts: 492
• 1
With the ternary operator a boolean expression is evaluated, if it is true the code before the colon is executed if it is false the code after the colon is evaluated.
(<boolean expression> ? "if true do this" : "if false do this").

It may be easier to see the answer to the nested example you posted if you draw it as a decision tree.

if the expression is true go down the left subtree, if false go down the right

Hope this helps,
Hunter

Bert Bates
author
Sheriff
Posts: 8900
5
This sample question is about 100x trickier than anything you'll get on the real exam!

Rahul Sudip Bose
Ranch Hand
Posts: 637
Try it like this :
Single out each expression and replace it by the result, on paper. One line is enough.

true ? false ? "7" : false ? "6" : false ? true ? "5": >>>true ? "4" : "3"<<< : "2" :"1" ---> put 4 in place of expression.

true ? false ? "7" : false ? "6" : false ? >>>true ? "5": "4"<<< : "2" :"1" ---5

true ? false ? "7" : false ? "6" : >>>false ? "5" : "2"<<< :"1" ---etc

Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
@ Hunter McMillen : Hi, when you construct a tree, it is also important to tell that how to travel ?

Hunter McMillen
Ranch Hand
Posts: 492
Seetharaman Venkatasamy wrote:@ Hunter McMillen : Hi, when you construct a tree, it is also important to tell that how to travel ?

Yes, if you travel the wrong direction you will get the wrong answer. So if the condition you're evaluating is true go to the left child, if the condition is false, go to the right child.

Hunter