Java provides an alternate method of coding an if-else
statement using the conditional operator. This operator is the only ternary operator in Java, as it requires three operands. The general syntax is:
(condition) ? value1 : value2;
If the condition is true, value1
is returned. If the condition is false, value2
is returned.
This is appropriate in situations where the condition is fairly compact and the result is a value or object. Here are three examples.
/** returns the larger of two integers */
int max(int a, int b) {
return (a > b) ? a : b;
}
// bonus is set to $100 if more than 60 hours are worked, $0 otherwise
bonus = (hoursWorked > 60) ? 100 : 0;
// name is set to the cooler of the two people
name = (bobCoolFactor > joeCoolFactor) ? "Bob" : "Joe";
Last modified: December 12, 2022
Back to Nested If-else Statements