Unlimited web hosting - Chapter 4 Control Structures: Part 1 157 If
Chapter 4 Control Structures: Part 1 157 If studentGrade is greater than or equal to 90, the first four conditions will be true, but only the System.out.println statement after the first test will be executed. After that particular System.out.println is executed, the else part of the outer if/else statement is skipped. Good Programming Practice 4.4 If there are several levels of indentation, each level should be indented by the same additional amount of space. Most Java programmers prefer to write the preceding if structure as if ( grade >= 90 ) System.out.println( “A” ); else if ( grade >= 80 ) System.out.println( “B” ); else if ( grade >= 70 ) System.out.println( “C” ); else if ( grade >= 60 ) System.out.println( “D” ); else System.out.println( “F” ); Both forms are equivalent. The latter form is popular because it avoids the deep indentation of the code to the right. Such deep indentation often leaves little room on a line, forcing lines to be split and decreasing program readability. It is important to note that the Java compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). This attribute is referred to as the dangling-else problem. For example, if ( x > 5 ) if ( y > 5 ) System.out.println( “x and y are > 5″ ); else System.out.println( “x is <= 5" ); appears to indicate that if x is greater than 5, the if structure in its body determines if y is also greater than 5. If so, the string "xandyare>5″ is output. Otherwise, it appears that if x is not greater than 5, the else part of the if/else structure outputs the string “xis<=5". Beware! The preceding nested if structure does not execute as it would appear to. The compiler actually interprets the preceding structure as if ( x > 5 ) if ( y > 5 ) System.out.println( “x and y are > 5″ ); else System.out.println( “x is <= 5" ); in which the body of the first if structure is an if/else structure. This structure tests if x is greater than 5. If so, execution continues by testing if y is also greater than 5. If the second condition is true, the proper string "xandyare>5″ is displayed. However, if the second condition is false, the string “xis<=5″is displayed, even though we know that x is greater than 5. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01