是的,它是一种速记形式
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
它被称为条件运算符。许多人(错误地)称之为三元运算符,因为它是Java,C,C和可能许多其他语言中唯一的三元(三参数)运算符。但是理论上可以有另一个三元运算符,而只能有一个条件运算符。
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
请注意,两个分支都必须使用带有返回值的方法:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (07001), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
所以,如果doSomething()和doSomethingElse()是void方法,你不能压缩这:
if (someBool)
doSomething();
else
doSomethingElse();
进入:
someBool ? doSomething() : doSomethingElse();
简单词:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse