Reputation: 167
What do the symbols '?' and ':' mean in a return statement?
public boolean isItBigger(BigInteger num1, Long num2) {
return num1 == BigInteger.ONE || num2.intValue() > 0 ? true : false;
}
Also I think I have seen them in if statements.
Upvotes: 0
Views: 94
Reputation: 19466
It's a ternary operator. The following are equivalent
if (x == y)
x = 2;
else
x = 3;
and
x = (x == y) ? 2 : 3;
Your example code is silly though. First they're checking if the expression evaluates to true. Then, if it does, they return true. They could just as well return the result of expression itself, like so:
return num1 == BigInteger.ONE || num2.intValue() > 0;
Upvotes: 1
Reputation: 6622
this is called conditional/ternary operator
boolean-expression ? do-this-if-true : else-do-this
it is shortened form of
if (boolean-expression) {
do-this
} else{
do-this
}
Upvotes: 0
Reputation: 178253
Using ?
and :
is Java's ternary conditional operator (JLS 15.25). The result of the expression
aBoolean ? expr1 : expr2
is expr1
if aBoolean
is true
, else it's expr2
.
In this case, it could be left off because it's unnecessary:
return num1 == BigInteger.ONE || num2.intValue() > 0;
Upvotes: 4