3.6. Formatting Console Output and Strings

 
[Page 83 ( continued )]

3.5. Conditional Expressions

You might want to assign a value to a variable that is restricted by certain conditions. For example, the following statement assigns 1 to y if x is greater than , and “1 to y if x is less than or equal to .

   if   (x >     )   y =   1     else   y =   -1   ; 

Alternatively, as in this example, you can use a conditional expression to achieve the same result.

 y = (x >     )   ?     1     :     -1   ; 


[Page 84]

Conditional expressions are in a completely different style, with no explicit if in the statement. The syntax is shown below:

 booleanExpression ? expression1 : expression2; 

The result of this conditional expression is expression1 if booleanExpression is true ; otherwise the result is expression2 .

Suppose you want to assign the larger number between variable num1 and num2 to max . You can simply write a statement using the conditional expression:

 max = (num1 > num2) ? num1 : num2; 

For another example, the following statement displays the message "num is even" if num is even, and otherwise displays "num is odd."

 System.out.println((num %   2   ==     ) ?   "num is even"   :   "num is odd"   ); 

Note

The symbols ? and : appear together in a conditional expression. They form a conditional operator . This operator is called a ternary operator because it uses three operands. It is the only ternary operator in Java.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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