Page 153 - Introduction to Programming with Java: A Problem Solving Approach
P. 153

                4.7 switch Statement
The switch statement works similarly to the “if, else if” form of the if statement in that it allows you to follow one of several paths. But a key difference between the switch statement and the if statement is that the switch statement’s determination of which path to take is based on a single value. (With an if state- ment, the determination of which path to take is based on multiple conditions, one for each path.) Having the determination based on a single value can lead to a more compact, more understandable implementation. Think of driving on Route 1 along the California coastline and coming to a junction with alternate routes through and around a city. The different routes are better at certain times of the day. If it’s 8 am or 5 pm, you should take the outer business loop to avoid rush-hour traffic. If it’s 8 pm, you should take the coastal bluffs route to appreciate the scenic sunset view. If it’s any other time, you should take the through-the-city route because it is the most direct and fastest. Using a single value, time of day, to determine the route parallels the decision-making process in a switch statement.
          Apago PDF Enhancer
Syntax and Semantics
Study the switch statement’s syntax in Figure 4.8. When executing a switch statement, control jumps to the case constant that matches the controlling expression’s value, and the computer executes all subsequent statements up to a break statement. The break statement causes control to exit from the switch state- ment (to below the closing brace). If there are no case constants that match the controlling expression’s value, then control jumps to the default label (if there is a default label) or out of the switch state- ment if there is no default label.
Usually, break statements are placed at the end of every case block. That’s because you normally want to execute just one case block’s subordinate statement(s) and then exit the switch statement. How- ever, break statements are not required. Sometimes you want to omit them, and being able to omit them is a special feature of the switch construct. But accidentally forgetting to include a break statement that should be included is a common error. If there’s no break at the bottom of a particular case block, control flows through subsequent case constants and executes all subordinate statements until a break statement
4.7 switch Statement 119
  



























































































   151   152   153   154   155