Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
user2097211 Avatar asked Aug 09 '13 12:08

user2097211


1 Answers

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());
like image 108
assylias Avatar answered Nov 09 '22 21:11

assylias