{condition-to-evaluate} ? {statement-executed-on-true} : {statement-executed-on-false}
As shown in the syntax, the Conditional Operator (also known as the Ternary Operator1) uses the ?
(question mark) and :
(colon) characters to enable a conditional expression of two possible outcomes. It can be used to replace longer if-else
blocks to return one of two values based on condition.
result = testCondition ? value1 : value2
Is equivalent to
if (testCondition) {
result = value1;
} else {
result = value2;
}
It can be read as “If testCondition is true, set result to value1; otherwise, set result to value2”.
For example:
// get absolute value using conditional operator
a = -10;
int absValue = a < 0 ? -a : a;
System.out.println("abs = " + absValue); // prints "abs = 10"
Is equivalent to
// get absolute value using if/else loop
a = -10;
int absValue;
if (a < 0) {
absValue = -a;
} else {
absValue = a;
}
System.out.println("abs = " + absValue); // prints "abs = 10"
You can use the conditional operator for conditional assignments (like null checking).
String x = y != null ? y.toString() : ""; //where y is an object
This example is equivalent to:
String x = "";
if (y != null) {
x = y.toString();
}
Since the Conditional Operator has the second-lowest precedence, above the Assignment Operators, there is rarely a need for use parenthesis around the condition, but parenthesis is required around the entire Conditional Operator construct when combined with other operators:
// no parenthesis needed for expressions in the 3 parts
10 <= a && a < 19 ? b * 5 : b * 7
// parenthesis required
7 * (a > 0 ? 2 : 5)
Conditional operators nesting can also be done in the third part, where it works more like chaining or like a switch statement.