问题描述
我碰到这样的语法来了:
I came across this syntax:
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(布尔"打印真QUOT;:"打印假")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!