user2097211
user2097211

Reputation: 333

Java Ternary Operator inside ternary operator, how evaluated?

Very basic question I suppose, I just wanted to know how this code is read:

return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance(); 

I guess now as I'm writing it I kind of understand the statement. It returns option one if true but then does another boolean check if false and returns one of the two remaining options? I'm going to continue to leave this question because I have not seen it before and maybe others have not as well.

Could you go on indefinitely with ternary inside of ternary operations?

Edit: Also why is this/is this not better for code than using a bunch of if statements?

Upvotes: 6

Views: 12576

Answers (2)

Duncan Jones
Duncan Jones

Reputation: 69409

Ternary operators are right-associative. See assylias's answer for the JLS reference.

Your example would translate to:

if (someboolean) {
  return new someinstanceofsomething();
} else {
  if (someotherboolean) {
    return new otherinstance();
  } else {
    return new thirdinstance()
  }
}

And yes, you can nest these indefinitely.

Upvotes: 7

assylias
assylias

Reputation: 328913

It is defined in JLS #15.25:

The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

In your case,

return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance();

is equivalent to:

return someboolean ? new someinstanceofsomething() : (someotherboolean ? new otherinstance() : new third instance());

Upvotes: 17

Related Questions