The switch is sometimes classified as a selection statement. The switch statement selects from among pieces of code based on the value of an integral expression. Its 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 integralselector to each integral-value. If it finds a match, the corresponding statement (simple or compound) executes. If no such match occurs, the default statement executes.
You will notice in the above 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 execute until a break is encountered. Although you don’t usually want this kind of behavior, it will be useful to an experienced programmer.
Note the last statement, for 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 multi-way 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 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. Here is an example that creates letters randomly and determines whether they are vowels or consonants.
public class VowelsAndConsonants
{
public static void main(String[] args)
{
for(int i=0;i<100;i++)
char c=(char((Math.random()*26+'a')
System.out.print(c+": ");
switch(c){
case 'a';
case 'e';
case 'i';
case 'o';
case 'u';
System.out.println("vowel");
break;
case 'y';
case 'w';
System.out.println(“Sometimes a vowel”);
break;
default;
System.out.println("consonant");
}
}
}
}
