Java ternary operator with empty clause

一笑奈何 提交于 2019-12-10 14:29:33

问题


This question is more for my curiosity than anything else.

I often employ Java's ternary operator to write shorter code. I have been wondering, however, whether it is possible to use it if one of the if or else conditions are empty. In more details:

int x = some_function();
if (x > 0)
    x--;
else
    x++;

can be written as x = (x > 0) ? x-1 : x+1;

But is it possible to write if (x > 0) x-1; as a ternary expression with an empty else clause?


回答1:


But is it possible to write if (x > 0) x--; as a ternary expression with an empty else clause?

No, the conditional operator requires three operands. If you wanted, you could do this:

x = (x > 0) ? x - 1 : x;

...but (subjectively) I think clarity suffers.



来源:https://stackoverflow.com/questions/19687589/java-ternary-operator-with-empty-clause

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