Java Reference
In-Depth Information
The Conditional Operator
An alternative to using the if and else keywords in a conditional statement is to use the
conditional operator, sometimes called the ternary operator . The conditional operator is
called a ternary operator because it has three operands.
The conditional operator is an expression, meaning that it returns a value—unlike the
more general if , which can result in only a statement or block being executed. The con-
ditional operator is most useful for short or simple conditionals and looks like the follow-
ing line:
test ? trueresult : falseresult ;
The test is an expression that returns true or false , just like the test in the if state-
ment. If the test is true , the conditional operator returns the value of trueresult . If the
test is false , the conditional operator returns the value of falseresult . For example,
the following conditional tests the values of myScore and yourScore , returns the larger of
the two as a value, and assigns that value to the variable ourBestScore :
int ourBestScore = myScore > yourScore ? myScore : yourScore;
This use of the conditional operator is equivalent to the following if - else code:
int ourBestScore;
if (myScore > yourScore)
ourBestScore = myScore;
4
else
ourBestScore = yourScore;
The conditional operator has a low precedence—usually it is evaluated only after all its
subexpressions are evaluated. The only operators lower in precedence are the assignment
operators. For a refresher on operator precedence, refer to Table 2.6 in Day 2, “The
ABCs of Programming.”
The ternary operator is of primary benefit to experienced program-
mers creating complex expressions. Its functionality is duplicated
in simpler use of if - else statements, so there's no need to use
this operator while you're beginning to learn the language. The
main reason it's introduced in this topic is because you'll
encounter it in the source code of other Java programmers.
CAUTION
Search WWH ::




Custom Search