Java Reference
In-Depth Information
if (number > 0) {
System.out.println("Number is positive.");
}
if (number == 0) {
System.out.println("Number is zero.");
}
if (number < 0) {
System.out.println("Number is negative.");
}
No
Ye s
Is test1 true?
statement1
No
Ye s
Is test2 true?
statement3
statement2
Figure 4.5
Flow of nested if s ending in else
To determine how many of the println s are potentially executed, you have
to stop and think about the tests being performed. But you shouldn't have to put that
much effort into understanding this code. The code is clearer if you nest the if
statements:
if (number > 0) {
System.out.println("Number is positive.");
} else if (number == 0) {
System.out.println("Number is zero.");
} else if (number < 0) {
System.out.println("Number is negative.");
}
This solution has a problem, however. You know that you want to execute one and
only one println statement, but this nested structure does not preclude the possibil-
ity of no statement being executed (which would happen if all three tests failed).
Of course, with these particular tests that will never happen: If a number is neither
positive nor zero, it must be negative. Thus, the final test here is unnecessary and
 
 
Search WWH ::




Custom Search