The Conditional Operator

   

The conditional operator is unique because it is the one ternary, or triadic, operator in Java. This distinction means that it is the only operator that acts on three operands in an expression (instead of the typical one or two). It functions in Java as it does in C and C++, and takes the following form:

 expression1 ? expression2 : expression3 

In this syntax, expression1 must evaluate to a Boolean value. If this value is true, then expression2 is evaluated, and its result is the value of the conditional. If expression1 is false, then expression3 is evaluated, and its result is the value of the conditional. You can look at the ternary operator just as if it were a typical if - else statement:

 if (expression1) {   expression2; } else {   expression3; } 

Consider the following examples. The first uses the conditional operator to determine the maximum of two values; the second determines the minimum of two values; the third determines the absolute value of a quantity.

 bestReturn = stockReturn > bondReturn ? stockReturn : bondReturn; lowSales = juneSales < julySales ? juneSales : julySales; distance = site1-site2 > 0 ? site1-site2 : site2-site1; 

The purpose of the ternary operator is not only to cause a specific operand to be evaluated, but to produce a result that can be assigned to a variable or used in another expression or a method call. Remember that the result of any Java expression must be used or a compiler error results.

 // this statement causes a compiler error because the result // of the expression is not used stockReturn > bondReturn ? stockReturn : bondReturn; 

In reviewing these examples, think about the precedence rules and convince yourself that none of the three examples requires any parentheses to be evaluated correctly. You might want to use parentheses to make code that uses the conditional operator easier to read, but this operator has very low precedence, so its operands are obvious to the compiler.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net