| |
Conditional Operator | page 12 of 15 |
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) ? statement1 : statement2;
If the condition is true, statement1 is executed. If the condition is false, statement2 is executed.
This is appropriate in situations where the conditions and statements are fairly compact.
int max(int a, int b) // returns the larger of two integers
{
(a > b) ? return a : return b;
}
|