符号'?'是什么意思?和“:”是否在回复声明中表示?返回语句语法
public boolean isItBigger(BigInteger num1, Long num2) {
return num1 == BigInteger.ONE || num2.intValue() > 0 ? true : false;
}
另外我想我已经看到他们在if语句。
符号'?'是什么意思?和“:”是否在回复声明中表示?返回语句语法
public boolean isItBigger(BigInteger num1, Long num2) {
return num1 == BigInteger.ONE || num2.intValue() > 0 ? true : false;
}
另外我想我已经看到他们在if语句。
使用?
和:
是Java的ternary conditional operator(JLS 15.25)。表达
aBoolean ? expr1 : expr2
的结果是expr1
如果aBoolean
是true
,否则它是expr2
。
在这种情况下,它可以离开,因为这是不必要的:
return num1 == BigInteger.ONE || num2.intValue() > 0;
我现在明白了,你说得对, FALS最后的表达。感谢所有人的回应。 – Blackmore
这是一个ternary operator。以下是等价
if (x == y)
x = 2;
else
x = 3;
和
x = (x == y) ? 2 : 3;
你的示例代码是愚蠢不过。首先他们检查表达式是否为真。那么,如果是这样,他们将返回true。他们可能只是以及返回表达式本身的结果,就像这样:
return num1 == BigInteger.ONE || num2.intValue() > 0;
这被称为条件/三元运算符
boolean-expression ? do-this-if-true : else-do-this
它缩短的
if (boolean-expression) {
do-this
} else{
do-this
}
形式是相同的作为'返回(num1 == BigInteger.ONE || num2.intValue()> 0);' – assylias
现在我明白了,谢谢大家的回应:) – Blackmore