Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^456) | Exceptions and Additional Control Structures


The ?: Operator


The last operator shown in Table 9.1 is the ?:operator, sometimes called the conditional op-
erator. This ternary (three-operand) operator has the following syntax:

Here’s how it works. First, the computer evaluates Expression1. If the value is true, then
the value of the entire expression is Expression2; otherwise, the value of the entire expres-
sion is Expression3.
A classic example of the conditional operator’s use is to set a variable maxequal to the
larger of two variables aand b. Using an ifstatement, we would do it this way:

if (a > b)
max = a;
else
max = b;

With the ?:operator, we can use the following assignment statement:

max = (a > b)? a : b;

The ?:operator is certainly not an intuitively obvious bit of Java syntax; it’s one of the
unusual features that Java inherited from C. We do not use it in this book, but you should be
aware of it in case you encounter it when reading code written by someone else.

Operator Precedence


Table 9.2 summarizes the rules of operator precedence for the Java operators we have en-
countered so far, excluding the bitwise operators. (Appendix B contains the complete list.)
In the table, the operators are grouped by precedence level, and a horizontal line separates
each precedence level from the next-lower level.
The column labeled Associativitydescribes the grouping order. Within a precedence level,
most operators are grouped from left to right. For example,

a – b + c

Expression1? Expression2 : Expression3

Conditional-Expression
Free download pdf