java - 什么是 Java ? : operator called and what does it do?

标签 java syntax ternary-operator conditional-operator

我已经使用 Java 几年了,但直到最近我还没有遇到过这种结构:

int count = isHere ? getHereCount(index) : getAwayCount(index);

这可能是一个非常简单的问题,但有人可以解释一下吗?我该如何阅读?我很确定我知道它是如何工作的。

  • 如果 isHere 为真,则调用 getHereCount()
  • 如果 isHere 为 false,则调用 getAwayCount()

对吗?这个结构叫什么?

最佳答案

是的,它是一种简写形式

int count;
if (isHere)
    count = getHereCount(index);
else
    count = getAwayCount(index);

称为条件运算符。许多人(错误地)称它为 三元运算符,因为它是 Java、C、C++ 以及可能许多其他语言中唯一的三元(三参数)运算符。但是理论上可能还有一个三元运算符,而条件运算符只能有一个

官方名称在 Java Language Specification 中给出:

§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 (§14.8), 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 

关于java - 什么是 Java ? : operator called and what does it do?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/798545/

相关文章:

java - 如何使用 Gradle 将源代码发布到本地 Maven 存储库?

html - CSS 网格 - 为什么 "justify-items"变灰但有效?

java - 使用三元运算符与 if else 与 switch case 的比较(性能)

Java 三元运算符函数重载

java - Solr 为 "Standalone binary in Desktop Client"没有服务器

Java Spring Boot - spring-boot-starter-tomcat 依赖项不适用于在本地运行时提供的范围

java - 发送commit_sm请求时,Restcomm SMSC会继续引发ActivityAlreadyExistsException

c# - 显式变量声明

c# - 如何检查字符串是否具有正确的html语法

c++ - gcc 关于字符串类型不一致