The Conditional Operator
The conditional operator is unique because it is the one ternary, or triadic, operator in Java. This distinction means that it is the only operator that acts on three operands in an expression (instead of the typical one or two). It functions in Java as it does in C and C++, and takes the following form:
expression1 ? expression2 : expression3
In this syntax, expression1 must evaluate to a Boolean value. If this value is true, then expression2 is evaluated, and its result is the value of the conditional. If expression1 is false, then expression3 is evaluated, and its result is the value of the conditional. You can look at the ternary operator just as if it were a typical if-else statement:
if (expression1) { expression2; ...
Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.