Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • 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 ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

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

Ranch Hand
Posts: 61
Mac IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.

Posts: 3959
  • 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!
There's a hole in the bucket, dear Liza, dear Liza, a hole in the bucket, dear liza, a tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
    Bookmark Topic Watch Topic
  • New Topic