Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING

} else {
greeting += "evening";
}
System.out.println(greeting);


You probably knew what we were going to do with that greeting string.
Notice the else if structure. We can attach additional if statements to our else statements. In this
fashion, it's possible to step through any number of alternatives, providing a different behavior for each
one. If you step through the code with various values (try 10, 13, and 19), you can see how any possible
value gets caught and sets the greeting string appropriately. The key to that capability is the final else,
which does not check for any condition. In this case, that's just a convenience that lets us avoid writing
if (hour < 24).
Sometimes, though, you want to use a final else to catch problems. In many real-world programs, a
set of if-else statements catches all the expected conditions, whereas the final condition-free else
statement throws an exception (which means the program lets us know that it found a problem) because
the program found an unexpected condition. That's another example of defensive coding to put in your
programming toolkit.
Let's consider a larger example in Listing 5-4, to show the mechanism in greater detail.


Listing 5-4. A larger else-if example


GregorianCalendar gregorianCalendar = new GregorianCalendar();
int day = gregorianCalendar.get(Calendar.DAY_OF_WEEK);
String greeting = "Good ";
if (day == 1) {
greeting += "Sunday";
} else if (day == 2) {
greeting += "Monday";
} else if (day == 3) {
greeting += "Tuesday";
} else if (day == 4) {
greeting += "Wednesday";
} else if (day == 5) {
greeting += "Thursday";
} else if (day == 6) {
greeting += "Friday";
} else if (day == 7) {
greeting += "Saturday";
}
greeting += " to you.";
System.out.println(greeting );


Notice that we don’t put in a final else statement. In this case, we know that the GregorianCalendar
class can't produce values we don't expect (it instead throws an exception before even getting to our if
statements), so there's no need for it. Use that final else trick when you can't be sure you'll always get an
expected condition or (as in the earlier example) when you can use it as a shortcut.


switch Statements


The switch keyword lets us set up a structure that does the same thing as a set of if-else statements but
that uses a different syntax. Personally, I'm so accustomed to reading if-else blocks that we prefer them,

Free download pdf