IN THIS CHAPTER
Avoiding the trouble with big else-if statements
Using the switch statement
Creating case groups
Using characters with case
In Book 2, Chapter 4, you find out about the workhorses of Java decision-making:
boolean expressions and the mighty
if statement. In this chapter, you discover another Java tool for decision-making: the
switch statement. The
switch statement is a pretty limited beast, but it excels at making one particular type of decision: choosing one of several actions based on a value stored in an integer variable. As it turns out, the need to do just that comes up a lot. You want to keep the
switch statement handy for use when such a need arises.
Many applications call for a simple logical selection of things to be done depending on some value that controls everything. As I describe in Book 2, Chapter 4, such things are usually handled with big chains of
else-if statements all strung together.
Unfortunately, these things can quickly get out of hand.
else-if chains can end up looking like DNA ...