3.3. The Conditional Operator

The conditional operator is sometimes called a ternary operator because it involves three operands. It is best understood by looking at an example. Suppose you have two variables of type int with the names yourAge and myAge, and you want to assign the greater of the values stored in yourAge and myAge to a third variable, older, which is also of type int. You can do this with the following statement:

older = yourAge>myAge ? yourAge : myAge;

The conditional operator has a logical expression as the first of its three operands—in this case, it is the expression yourAge>myAge. If this expression is true, the operand that follows the ? symbol—in this case, yourAge—is evaluated to produce the value resulting from the operation. If the expression yourAge>myAge is false, the third operand which comes after the colon—in this case, myAge—is evaluated to produce the value from the operation. Thus, the result of this conditional expression is yourAge, if yourAge is greater than myAge, and myAge otherwise. This value is then stored in the variable older. The use of the conditional operator in this assignment statement is equivalent to the if statement:

if(yourAge > myAge) {
  older = yourAge;
} else {
  older = myAge;
}

Remember, though, the conditional operator is an operator and not a statement, so you can use it in a more complex expression involving other operators.

The conditional operator can be written generally as:

logical_expression ? expression1 : expression2 ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th 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.