Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# ternary operator

Marcelo Ribeiro
Greenhorn

Joined: Aug 04, 2007
Posts: 9
Hello,

Kathy's book has this exercise:

the output is "everthing" but from my understandig it would be "universe"

x = (boolean expression) ? value to assign if true : value to assign if false

On that question it evaluates the first to false which route the code flow to another condition (i>50)?"universe":"everything"; which is true, so the output would be "universe", could anyone please explain this?

Karthik Gurukuntala
Greenhorn

Joined: Jun 27, 2007
Posts: 5
Friend,
i = 42;
42 is not greater than 50.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

If i<40, then the ternary returns "life." Otherwise, a second (nested) ternary is evaluated. In the second ternary, if i>50, then it returns "universe." Otherwise, it returns "everything."

In this example, i is 42. So i<40 evaluates to false, and so the second ternary evaluated. In the second ternary, i>50 also evaluates to false, and so "everything" is returned.

This is a shorthand way of writing...

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 13543

6

It's on page 301 of the book and it should read:

String s = (i<40)?"life"i>50)?"universe":"everything";

(The is unfortunately interpreted as a sad smiley in your post - note that there's an option to disable smileys when you write a post).
Originally posted by marcelo ribeiro:
On that question it evaluates the first to false which route the code flow to another condition (i>50)?"universe":"everything"; which is true, so the output would be "universe", could anyone please explain this?

Your logic about the flow is correct, but i is 42, so i > 50 is false, not true - so the anwer is "everything".
[ August 27, 2007: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Marcelo Ribeiro
Greenhorn

Joined: Aug 04, 2007
Posts: 9
ohh....you're right:

i = 42;
42 is not greater than 50.

I'm becoming crazy studying for this....thank you!!!

It is sorta covered in the JavaRanch Style Guide.

subject: ternary operator