Another very unique flow-control statement used to
select code to execute is the switch-case.
The switch-case is used when the value of one integer or character is
used to decide which code to execute. An example:
int choice;
System.out.print("What is your
choice (1, 2, or 3)? ");
choice = Stdin.readInt();
switch(choice) {
case
1: System.out.println("You said one.");
break;
case 2: System.out.println("You said
two.");
break;
case 3: System.out.println("You said
three.");
System.out.println("Aren't you cool?");
break;
default: System.out.println("That's not a
choice."); }
When this code is executed, the value of choice will
be compared to the numbers that appear by the word case. The list
will be searched from beginning to end, until a matching number is
found. Once a match is found, all of the code after the colon
will be executed until a break
statement is hit. The numbers by the case's must be int literals or
char literals. If no match is found, the code after the word default will be executed.
The default section is
optional. If it is not there, nothing in the switch-case will be
executed when no match is found. Since the comparisons are done
to literals, the switch-case is not a good choice when you want to
compare to a range. Since the code in a switch-case will continue
executing until a break
statement or the end of the switch-case is reached, execution can
continue from one case to the next if there is no break statement. This is
called fall-through, and it
can be useful:
int choice;
System.out.print("What is your
choice (1, 2, or 3)? ");
choice = Stdin.readInt();
switch(choice) {
case
1: System.out.print("One little...");
case 2: System.out.print("Two
little...");
case 3: System.out.print("Three
little...");
default: System.out.println("Java programs.");
}
but the vast majority of the time fall-through happens in a
switch-case, it's the result of a mistake.