什么是 Java ?: 运算符,它有什么作用? [英] What is the Java ?: operator called and what does it do?

查看:31
本文介绍了什么是 Java ?: 运算符,它有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been working with Java a couple of years, but up until recently I haven't run across this construct:

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

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

This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.

  • 如果isHere为真,则调用getHereCount()
  • 如果 isHere 为假 getAwayCount() 被调用.
  • if isHere is true, getHereCount() is called,
  • if isHere is false getAwayCount() is called.

正确吗?这个结构叫什么?

Correct? What is this construct called?

推荐答案

是的,它是

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

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

It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.

官方名称在Java 语言规范:

条件运算符?: 使用一个表达式的布尔值来决定应该评估另外两个表达式中的哪一个.

§15.25 Conditional Operator ? :

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

注意,两个分支都必须指向有返回值的方法:

Note that both branches must lead to methods with return values:

第二个或第三个操作数表达式调用 void 方法是编译时错误.

其实是通过表达式语句的语法(§14.8),条件表达式不允许出现在任何可能出现 void 方法调用的上下文中.

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() 是空方法,你不能压缩这个:

So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:

if (someBool)
    doSomething();
else
    doSomethingElse();

进入这个:

someBool ? doSomething() : doSomethingElse();

简单的词:

booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse 

这篇关于什么是 Java ?: 运算符,它有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆