Java Reference
In-Depth Information
Note Switches were extended in Java 7 to allow the use of strings as switch
variables. To use a string as your variable and label, just include the label in
quotation marks so it is recognized as a string. For example:
char initial;
String myName = "Bob";
switch (myName) {
case "Ann": initial = 'A'; break;
case "Bob": initial = 'B'; break;
case "Claire": initial = 'C'; break;
default: initial = '?'; break;
}
Notice the three new keywords in the syntax: case , break , and default . Cases are similar to the
if() and else if() parts of an if-then statement. Each case is labeled with one possible value
the variable might take. If the label matches the value of the variable, the statements that follow
the : for that case will be executed. Cases are evaluated sequentially, from top to bottom. Once
a match is found, all the statements to follow will be executed, even those intended for the other
cases that follow. In order to prevent this from happening, the break keyword is used. The break
keyword is discussed more in detail in the next section, but its purpose is to break out of the
switch and continue with the rest of the program. default is the switch equivalent of the else
clause in an if-then statement. If none of the explicit cases apply to the variable, default will
still apply. Every value will match the default case, so this can be useful to handle unexpected
situations.
Because a switch is organized into cases, it makes sense to use it when you have a finite number of
expected values. Twelve months in a year, for example, could be represented by twelve cases. If the
situation calls for a large range of values, it's more suited to an if-then statement. Recall the example
concerning bank account alerts, where depending on if accountBalance was less than 0 , greater
than 100 , or somewhere in between, a message was displayed.
Imagine you want to include a switch in a bookkeeping program that determines the last day of
each month for recording monthly income and expenses. It might look something like this:
int month = 4; // here 4 represents April
int lastDay;
boolean leapYear = false;
switch (month) {
case 1: lastDay = 31; break;
case 2: if (leapYear == true) {
lastDay = 29;
} else {
lastDay = 28;
} break;
case 3: lastDay = 31; break;
case 4: lastDay = 30; break;
Search WWH ::




Custom Search