You have already seen a multiway structure created through the nesting of if … else structure. In this section, a new structure called switch is presented. Th e general syntax of the switch statement is as follows:
switch(expression)
Note that break, case, default, and switch are reserved words and statements-One, statementsTwo, and so on can be one or more executable statements. Th e semantics of the switch statement can be explained as follows. First, the expression is evaluated.
If the value of the expression is equal to valueOne, then statementsOne are exe-cuted. If the break statement is present, then no other statements within the structure are executed. However, if there is no break statement, statementsTwo are executed. If the break statement is present, then no other statements within the structure are executed.
However, if there is no break statement, statementsThree are executed, and so on.
Similarly, if the value of the expression is equal to valueTwo, then state-mentsTwo are executed. If the break statement is present, then no other statements within the structure are executed. However, if there is no break statement, statement-sThree are executed, and so on. If none of the values listed in case statements match the expression, then statementsD are executed.
Th e value of expression can only be an integral or enumerated data type; and is called the controlling expression. Th e enumerated data types will be introduced in the next section.
Th e literal value that appears aft er a case in a case statement is called a label. A specifi c label can appear only in one case statement and a case statement can list only one label.
Apago PDF Enhancer
However, you can list case statements one aft er another without any action statements for all of them except the last one. Th us, all these case statements will have the same action statements. Since syntax allows us to have multiple statements corresponding to a case, there is no need to use braces. All break statements are optional. In particular, the break state-ment associated with default value has no signifi cance at all and can be omitted.
Th e semantics of a switch structure can be summarized as follows (see Figure 4.8):
1. If the expression evaluates to a case label, then the statements are executed starting from that matching label until either a break statement or end of the switch structure is encountered. Once a break statement is encountered, no other statement in the switch structure is executed.
2. If the expression evaluates to a value that does not exist as a case label, then statements are executed starting from the label default.
3. If the expression evaluates to a value that does not exist and the switch struc-ture has no default label, then no statement in the switch strucstruc-ture is executed.
Example 4.23
A university’s admission criteria include points of the athletic participation. Th e points are awarded as follows: 25 points for international level participation, 18 points for national level participation, 12 points for state level participation, 6 points for district level participation, and 3 points for school level participation. Th is situ-ation can be coded using a switch statement as follows:
switch(participationLevel)
Apago PDF Enhancer
false expression == valueOne
true
statementsOne break
expression ==valueTwo
true
statementsTwo break
false
expression
==valueThree
true
statementsThree break
false
expression == valueN
true
statementsN break
false
statementsD break
default
.. .
FIGURE 4.8 Th e control structure switch.
Apago PDF Enhancer
In this example, the control expression participationLevel is an int variable. Th e labels are int literals 1 through 5.
Th e above switch statement can be replaced by the following semantically equivalent multiway if … else statement:
if (participationLevel == 1) athleticPoints = 3;
else if (participationLevel == 2) athleticPoints = 6;
else if (participationLevel == 3) athleticPoints = 12;
else if (participationLevel == 4) athleticPoints = 18;
else if (participationLevel == 5) athleticPoints = 25;
else
athleticPoints = 0;
Self-Check
27. True or false: In the switch statement to compute the athletic points, the order of case statements is immaterial.
28. Is above statement true in general?
Advanced Topic 4.11: Sharing Code in a switch Statement Example 4.24
Th e following switch statement illustrates the sharing of common code for more than one label. Assume that month and numberOfDays are int variables and leap Year is a boolean variable.
switch(month) {
case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 :
numberOfDays = 31;
break;
case 2 :
if (leapYear)
numberOfDays = 29;
Apago PDF Enhancer
Th e above switch statement can be replaced by the following if … else statement:
A credit card company issues four diff erent types of credit cards: basic, silver, gold, and platinum. As one moves up the level, one has all the benefi ts of the level below and some additional benefi ts. A switch statement is quite useful in this context.
System.out.println("You are entitled to the following:");
System.out.println();
switch(cardType) {
case 1 : //platinum
System.out.println("\t$100,000 in travel insurance");
case 2 : //gold
System.out.println("\tThree month price protection");
case 3 : //silver
System.out.println("\tFree rental car insurance");
Apago PDF Enhancer
case 4 : //basic
System.out.println("\tFree credit protection against loss");
System.out.println("\t24/7 toll free customer service");
System.out.println();
break;
default :
// no action required.
}
Th e above code is equivalent to the following segment of code:
System.out.println("You are entitled to the following:");
System.out.println();
if (cardType == 1) //platinum {
System.out.println("\t$100,000 in travel insurance");
System.out.println("\tThree month price protection");
System.out.println("\tFree rental car insurance");
System.out.println("\tFree credit protection against loss");
System.out.println("\t24/7 toll free customer service");
System.out.println();
}
else if (cardType == 2) //gold {
System.out.println("\tThree month price protection");
System.out.println("\tFree rental car insurance");
System.out.println("\tFree credit protection against loss");
System.out.println("\t24/7 toll free customer service");
System.out.println();
}
else if (cardType == 3) //silver {
System.out.println("\tFree rental car insurance");
System.out.println("\tFree credit protection against loss");
System.out.println("\t24/7 toll free customer service");
System.out.println();
}
else //basic
{
System.out.println("\tFree credit protection against loss");
System.out.println("\t24/7 toll free customer service");
System.out.println();
}
Apago PDF Enhancer
Advanced Topic 4.12: Limitations of a switch Statement
As you can observe from the preceding examples, a switch statement can always be implemented as a multiway if … else structure. However, since switch statement relies on equality operator and the controlling expression cannot be a fl oating-point value, not every if … else structure can be replaced by an elegant switch statement. Even though there are no broadly accepted rules to determine whether or not to use a switch structure to implement multiway selections, readability and maintainability can be one of the criteria in your decision making. When an equality comparison is involved with three or more alternatives, a switch statement may be more readable.
Example 4.26
In this example, we make use of the code developed in Example 4.25 to gener-ate personalized messages for every customer. We begin by creating a Credit-CardCustomer class. Th is class has four data members: salutation, firstName, lastName, and cardType. Th e only application-specifi c method is create WelcomeMessage that returns a personalized message as a string.
/**
Credit card message generator class
*/
public class CreditCardCustomer {
private String salutation;
private String firstName;
private String lastName;
private int cardType;
/**
Creates and returns the customized message @return message as a string
*/
public String createWelcomeMessage() {