• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

OCA Java SE 8 study guide Question 7, Chapter 2, page 96

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have some problems to read and understand the order of the ternary operators:



Although parentheses are not required this example increase code readability:



But for me the readability is not better! For me it is more logical to apply ((x<4) ? 10 : 8) first and then (x>2). But in this example, when I do so,  I receive the same result: "8". Would it be always the same result if I begin with the inner ternary and after the with the outer. I tested with x=3 and both ways give me the same result!

Do we always apply the outside ternary operator? Or does it not matter?

(x>2) is true and now between which two numbers I have to select: 8 and 7? If this is right, I get "8". Then the second (x<4) is false and I now have only 10 and 8. Since (x<4) is false, I get "8" and "8" is the right answer.

But when I change the value of x to 1:

(x>2) is false also I get "7". (x<4) is true, then between 10 and 7 I get "10"?! But the right answer is "7". Why?

IS THIS THE ANSWER: When the first (x>2) is false the second (x<4) may never be evaluated?!

Now we have two ternary operators chained, is it also possible to chain more? But the more they are the more difficult is is it to read und understand.

Thanks for any explanation.

Mike
 
Saloon Keeper
Posts: 3289
145
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Mike,

you can always arrange the ternaries so that it becomes much more readable. For instance: in your example, and to answer your question, you could transform it to:
I always write my ternaries like this:

where a, b anc c are boolean expressions. As if it were a switch statement!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!