The Ternary Operator

The ternary operator ? :, also referred to as the conditional operator, has three operands and takes the following form:

						operand1 ? operand2 : operand3
					

The first operand must be of boolean type. The first operand is evaluated and if true, the value of the second operand is returned. In this case, evaluation of the third operand does not take place. If the value of the first operand is false, evaluation of the second operand is skipped, and the value of the third operand is returned. The Java compiler requires that the second and third operands be promotable (numeric values) or castable (object references) to a common type.

For example, the program shown in Listing 3.12 produces the output 0xx3xx6xx9.

Listing 3.12. Ternary.java—Using ...

Get Sun Certification Training Guide (310-025, 310-027): Java™ 2 Programmer and Developer Exams 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.