Java Reference
In-Depth Information
misleading. You must think about the tests to determine whether or not it is possible
for all three tests to fail and all three branches to be skipped.
In this case, the best solution is the nested if/else approach with a final branch
that is always taken if the first two tests fail:
if (number > 0) {
System.out.println("Number is positive.");
} else if (number == 0) {
System.out.println("Number is zero.");
} else {
System.out.println("Number is negative.");
}
You can glance at this construct and see immediately that exactly one println
will be executed. You don't have to look at the tests being performed in order to real-
ize this; it is a property of this kind of nested if/else structure. If you want, you can
include a comment to make it clear what is going on:
if (number > 0) {
System.out.println("Number is positive.");
} else if (number == 0) {
System.out.println("Number is zero.");
} else { // number must be negative
System.out.println("Number is negative.");
}
One final benefit of this approach is efficiency. When the code includes three
simple if statements, the computer will always perform all three tests. When the
code uses the nested if/else approach, the computer carries out tests only until a
match is found, which is a better use of resources. For example, in the preceding
code we only need to perform one test for positive numbers and at most two tests
overall.
When you find yourself writing code to choose among alternatives like these,
you have to analyze the particular problem to figure out how many of the branches
you potentially want to execute. If it doesn't matter what combination of branches
is taken, use sequential if statements. If you want one or none of the branches to
be taken, use nested if/else statements with a test for each statement. If you
want exactly one branch to be taken, use nested if/else statements with a final
branch controlled by an else rather than by a test. Table 4.3 summarizes these
choices.
 
Search WWH ::




Custom Search