Java Ternary Operator inside ternary operator, how evaluated?

别来无恙 提交于 2019-12-04 11:10:17

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());
Duncan Jones

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!