3.15 The Conditional Operator: ?


3.15 The Conditional Operator: ?

The ternary conditional operator allows conditional expressions to be defined. The operator has the following syntax:


<condition>   ?   <expression 1 >   :   <expression 2 >

If the boolean expression <condition> is true then <expression 1 > is evaluated; otherwise , <expression 2 > is evaluated. Of course, <expression 1 > and <expression 2 > must evaluate to values of compatible types. The value of the expression evaluated is returned by the conditional expression.

 boolean leapYear = false; int daysInFebruary = leapYear ? 29 : 28;   // 28 

The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left:


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



A Programmer[ap]s Guide to Java Certification
A Programmer[ap]s Guide to Java Certification
ISBN: 201596148
EAN: N/A
Year: 2003
Pages: 284

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