问题描述
我碰到这样的语法来:
System.out.println(boolean_variable ? "print true": "print false");
- 这两种点的语法是什么?
- 我在哪里可以找到有关它的信息?
- 它是仅适用于布尔值还是以其他不同的方式实现?
推荐答案
? :
是条件运算符一>。 (这不仅仅是:
部分 - 整个方法参数是示例中条件运算符的一种用法。)
? :
is the conditional operator. (It's not just the :
part - the whole of the method argument is one usage of the conditional operator in your example.)
它通常被称为三元运算符,但这只是其性质的一个方面 - 有三个操作数 - 而不是它的名字。如果将另一个三元运算符引入Java,则该术语将变得模糊不清。它被称为条件运算符,因为它具有条件(第一个操作数),然后确定评估其他两个操作数中的哪一个。
It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.
计算第一个操作数,然后 第二个或根据第一个操作数是真还是假来评估第三个操作数...最后结果为结果运营商。
The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.
这样的事情:
int x = condition() ? result1() : result2();
大致相当于:
int x;
if (condition()) {
x = result1();
} else {
x = result2();
}
重要的是不评估其他操作数。例如,这很好:
It's important that it doesn't evaluate the other operand. So for example, this is fine:
String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
这篇关于Java:println中的boolean(boolean?" print true":" print false")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!