Полезная информация

Java Language Reference

Previous Chapter 4
Expressions
Next
 

4.12 Conditional Operator

The conditional operator (? :) is a ternary operator. The operator selects one of two expressions for evaluation, based on the value of its first operand. In this way, the conditional operator is similar to an if statement. A conditional operator may appear in a conditional expression:

[Graphic: Figure from the text]

The conditional operator produces a pure value. Conditional expressions group from right to left. Consider the following expression:

g?f:e?d:c?b:a

It is equivalent to

g?f:(e?d:(c?b:a))

The first operand of the conditional operator must be of type boolean, or a compile-time error occurs. If the first operand evaluates to true, the operator evaluates the second operand (i.e., the one following the ?) and produces the pure value of that expression. Otherwise, if the first operand evaluates to false, the operator evaluates the third operand (i.e., the one following the :) and produces the pure value of that expression. Note that the conditional operator evaluates either its second operand or its third operand, but not both.

The second and third operands of the conditional operator may be of any type, but they must both be of the same kind of type or a compile-time error occurs. If one operand is of an arithmetic type, the other must also be of an arithmetic type. If one operand is of type boolean, the other must also be of type boolean. If one operand is a reference type, the other must also be a reference type. Note that neither the second nor the third operand can be an expression that invokes a void method.

The types of the second and third operands determine the type of pure value that the conditional operator produces. If the second and third operands are of different types, the operator may perform a type conversion on the operand that it evaluates. The operator does this to ensure that it always produces the same type of result for a given expression, regardless of the value of its first operand.

If the second and third operands are both of arithmetic types, the conditional operator determines the type of value it produces as follows:[6]

If the second and third operands are both of type boolean, the conditional operator produces a pure boolean value.

If the second and third operands are both reference types, the conditional operator determines the type of value it produces as follows:

References Arithmetic Types; Boolean Type; Boolean OR Operator ||; Expression 4; Order of Operations; Reference Types


Previous Home Next
Boolean Operators Book Index Assignment Operators

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java