생산자

29_[자바] switch

The switch is sometimes called a selection statement. The switch statement selects from among pieces of code based on the value of an integral expression. Its general form is:

switch(integral-selector) {

case integral-value1 : statement; break;

case integral-value2 : statement; break;

case integral-value3 : statement; break;

case integral-value4 : statement; break;

case integral-value5 : statement; break;

// ...

default: statement;

}

Integral-selector is an expression that produces an integral value. The switch compares the result of integral-selector to each integral-value. If it finds a match, the corresponding statement (a single statement or multiple statements; braces are not required) executes. If no match occurs, the default statement executes.

You will notice in the preceding definition that each case ends with a break, which causes execution to jump to the end of the switch body. This is the conventional way to build a switch statement, but the break is optional. If it is missing, the code for the following case statements executes until a break is encountered. Although you don’t usually want this kind of behavior, it can be useful to an experienced programmer. Note that the last statement, following the default, doesn’t have a break because the execution just falls through to where the break would have taken it anyway. You could put a break at the end of the default statement with no harm if you considered it important for style’s sake.

The switch statement is a clean way to implement multiway selection (i.e., selecting from among a number of different execution paths), but it requires a selector that evaluates to an integral value, such as int or char. If you want to use, for example, a string or a floating

point number as a selector, it won’t work in a switch statement. For non-integral types, you must use a series of if statements. At the end of the next chapter, you’ll see that Java SE5’s new enum feature helps ease this restriction, as enums are designed to work nicely with switch.

Since Random.nextInt(26) generates a value between 0 and 26, you need only add an offset of ‘a’ to produce the lowercase letters. The single-quoted characters in the case statements also produce integral values that are used for comparison.

Notice how the cases can be “stacked” on top of each other to provide multiple matches for a particular piece of code. You should also be aware that it’s essential to put the break statement at the end of a particular case; otherwise, control will simply drop through and continue processing on the next case.

In the statement:

int c = rand.nextInt(26) + ‘a’;

Random.nextInt( ) produces a random int value from 0 to 25, which is added to the value of ‘a’. This means that ‘a’ is automatically converted to an int to perform the addition.

In order to print c as a character, it must be cast to char; otherwise, you’ll produce integral output.