Http web server - 156 Control Structures: Part 1 Chapter 4 The
Monday, September 17th, 2007156 Control Structures: Part 1 Chapter 4 The conditional operator (?:) is related to the if/else structure. ?: is Java s only ternary operator it takes three operands. The operands together with ?: form a conditional expression. The first operand is a boolean expression, the second is the value for the conditional expression if the condition evaluates to true and the third is the value for the conditional expression if the condition evaluates to false. For example, the statement System.out.println( studentGrade>=60 ? “Passed”:”Failed” ); contains a conditional expression that evaluates to the string “Passed” if the condition studentGrade>=60 is true and to the string “Failed” if the condition is false. Thus, this statement with the conditional operator performs essentially the same function as the if/else statement given previously. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. We will see that conditional operators can be used in some situations where if/else statements cannot. Good Programming Practice 4.3 In general, conditional expressions are more difficult to read than if/else structures. Such expressions should be used with discretion when they help improve a program s readability. Nested if/else structures test for multiple cases by placing if/else structures inside if/else structures. For example, the following pseudocode statement prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades: If student s grade is greater than or equal to 90 Print A else If student s grade is greater than or equal to 80 Print B else If student s grade is greater than or equal to 70 Print C else If student s grade is greater than or equal to 60 Print D else Print F This pseudocode may be written in Java as if ( studentGrade >= 90 ) System.out.println( “A” ); else if ( studentGrade >= 80 ) System.out.println( “B” ); else if ( studentGrade >= 70 ) System.out.println( “C” ); else if ( studentGrade >= 60 ) System.out.println( “D” ); else System.out.println( “F” ); Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01