• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Nested Ternary operators

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would like to know how do nested Ternary operators work.There is a small code also which Im sending .
What I'm interested in knowing is when I run this code why is the output : The value of a is 4 .
[This message has been edited by dhruv simaria (edited April 04, 2001).]
[This message has been edited by dhruv simaria (edited April 04, 2001).]
 
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No offense, Dhruv, but I think that is the ugliest Java statement I have ever seen.
To evaluate it, you have to realize that the ternary operator is one of the few operators in Java that has right-to-left associativity. In other words, when confronted with nested ternary operators, Java starts evaluating the rightmost one and works its way left from there.
Given that piece of information, I will simplify your original statement, step-by-step. Keep in mind, Dhruv, each of these statements is equivalent:
<PRE>
Step 1: false ? true ? 1 : true ? 2 : 3 : true ? 4 : true ? 5 : 6
Step 2: false ? true ? 1 : true ? 2 : 3 : true ? 4 : 5
Step 3: false ? true ? 1 : true ? 2 : 3 : 4
Step 4: false ? true ? 1 : 2 : 4
Step 5: false ? 1 : 4
Step 6: 4
</PRE>
HTH
Art
 
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic