Java Reference
In-Depth Information
else if (month == 4)
//Line 7
System.out.println("April");
//Line 8
else if (month == 5)
//Line 9
System.out.println("May");
//Line 10
else if (month == 6)
//Line 11
System.out.println("June");
//Line 12
(b)
if (month == 1)
System.out.println("January");
if (month == 2)
System.out.println("February");
if (month == 3)
System.out.println("March");
if (month == 4)
System.out.println("April");
if (month == 5)
System.out.println("May");
if (month == 6)
System.out.println("June");
4
Program segment (a) is written as a sequence of if ... else statements; program segment
(b) is written as a series of if statements. Both program segments accomplish the same
thing. If month is 3 , then both program segments output March .If month is 1 , then in
program segment (a), the expression in the if statement in Line 1 evaluates to true . The
statement (in Line 2) associated with this if then executes. The rest of the structure,
which is the else of this if statement, is skipped, and the remaining if statements are
not evaluated. In program segment (b), the computer has to evaluate the logical expres-
sion in each if statement because there is no else statement. As a consequence, program
segment (b) executes more slowly than does program segment (a).
Short-Circuit Evaluation
Logical expressions in Java are evaluated using an efficient algorithm. This algorithm is
illustrated with the help of the following statements:
(x > y) || (x == 5)
(a == b) && (x >= 7)
In the first statement, the two operands of the operator || are the expressions (x > y) and
(x == 5) . This expression evaluates to true if either the operand (x > y) is true or the
operand (x == 5) is true . With short-circuit evaluation, the computer evaluates the
logical expression from left to right. As soon as the value of the entire logical expression
can be determined, the evaluation stops. For example, in the first statement, if the
operand (x > y) evaluates to true , then the entire expression evaluates to true because
true || true is true and true || false is true . Therefore, the value of the operand
(x == 5) has no bearing on the final outcome.
 
Search WWH ::




Custom Search