Section 3.6
The switch Statement
THE SECOND BRANCHING STATEMENT in Java is
the switch statement, which is introduced in this section.
The switch is used far less often than the if statement,
but it is sometimes useful for expressing a certain type of
multi-way branch. Since this section wraps up coverage of all of
Java's control statements, I've included a complete
list of Java's statement types at the end of the section.
A switch statement allows you to test the
value of an expression and, depending on that value, to jump to
some location within the switch statement. The expression must
be either integer-valued or character-valued. It
cannot be a String or a real number.
The positions that you can jump to are marked with "case labels" that
take the form: "case constant:".
This marks the position the computer jumps to when
the expression evaluates to the given constant.
As the final case in a switch statement you can, optionally,
use the label "default:", which provides a default
jump point that is used when the value of the expression is not
listed in any case label.
A switch statement has the form:
switch (expression) {
case constant-1:
statements-1
break;
case constant-2:
statements-2
break;
.
. // (more cases)
.
case constant-N:
statements-N
break;
default: // optional default case
statements-(N+1)
} // end of switch statement
The break statements are technically optional. The effect of a
break is to make the computer jump to the end of the switch
statement. If you leave out
the break statement, the computer will just forge ahead after completing
one case and will execute the statements associated with the next
case label. This is rarely what you want, but it is legal.
(I will note here -- although you won't understand it until
you get to the next chapter -- that inside a subroutine,
the break statement is sometimes replaced by a return statement.)
Note that you can leave out one of the groups of statements
entirely (including the break). You then have two case
labels in a row, containing two different constants. This just
means that the computer will jump to the same place and
perform the same action for each of the two constants.
Here is an example of a switch statement. This is not a useful
example, but it should be easy for you to follow. Note, by the
way, that the constants in the case labels don't have to be
in any particular order, as long as they are all different:
switch (N) { // assume N is an integer variable
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
The switch statement is pretty primitive as control structures
go, and it's easy to make mistakes when you use it. Java takes
all its control structures directly from the older programming
languages C and C++. The switch statement is certainly one place
where the designers of Java should have introduced some improvements.
One application of switch statements is in processing
menus. A menu is a list of options. The user selects one of the
options. The computer has to respond to each possible choice in
a different way. If the options are numbered 1, 2, ..., then
the number of the chosen option can be used in a switch
statement to select the proper response.
In a TextIO-based program, the menu can be presented as a numbered
list of options, and the user can choose an option by typing in its
number. Here is an example that could be used in a variation of
the LengthConverter example from the previous
section:
int optionNumber; // Option number from menu, selected by user.
double measurement; // A numerical measurement, input by the user.
// The unit of measurement depends on which
// option the user has selected.
double inches; // The same measurement, converted into inches.
/* Display menu and get user's selected option number. */
TextIO.putln("What unit of measurement does your input use?");
TextIO.putln();
TextIO.putln(" 1. inches");
TextIO.putln(" 2. feet");
TextIO.putln(" 3. yards");
TextIO.putln(" 4. miles");
TextIO.putln();
TextIO.putln("Enter the number of your choice: ");
optionNumber = TextIO.getlnInt();
/* Read user's measurement and convert to inches. */
switch ( optionNumber ) {
case 1:
TextIO.putln("Enter the number of inches: );
measurement = TextIO.getlnDouble();
inches = measurement;
break;
case 2:
TextIO.putln("Enter the number of feet: );
measurement = TextIO.getlnDouble();
inches = measurement * 12;
break;
case 3:
TextIO.putln("Enter the number of yards: );
measurement = TextIO.getlnDouble();
inches = measurement * 36;
break;
case 4:
TextIO.putln("Enter the number of miles: );
measurement = TextIO.getlnDouble();
inches = measurement * 12 * 5280;
break;
default:
TextIO.putln("Error! Illegal option number! I quit!");
System.exit(1);
} // end switch
/* Now go on to convert inches to feet, yards, and miles... */
The Empty Statement
As a final note in this section, I will mention one more
type of statement in Java: the empty statement.
This is a statement that consists simply of a semicolon. The existence of the
empty statement makes the following legal, even though you would
not ordinarily see a semicolon after a }.
if (x < 0) {
x = -x;
};
The semicolon is legal after the }, but the computer considers it
to be an empty statement, not part of the if statement. Occasionally, you might find yourself
using the empty statement when what you mean is, in fact, "do
nothing". I prefer, though, to use an empty block, consisting of
{ and } with nothing between, for such cases.
Occasionally, stray empty statements can cause annoying, hard-to-find
errors in a program. For example, the following program segment
prints out "Hello" just once, not ten times:
for (int i = 0; i < 10; i++);
System.out.println("Hello");
Why? Because the ";" at the end of the first line is
a statement, and it is this statement that is executed ten times.
The System.out.println statement is not really inside
the for statement at all, so it is executed just once,
after the for loop has completed.
A List of Java Statement Types
I mention the empty statement here mainly for completeness.
You've now seen just about every type of Java statement.
A complete list is given below for reference. The only new items
in the list are the try..catch, throw, and synchronized
statements, which are related to advanced aspects of Java known
as exception-handling and multi-threading, and the
return statement, which is used in subroutines. These will be
covered in later sections.
Another possible surprise is
what I've listed as "other expression statement,"
which reflects the fact that any expression followed by a semicolon
can be used as a statement. To execute such a
statement, the computer simply evaluates the expression,
and then ignores the value. Of course, this only makes sense
when the evaluation has a side effect
that makes some change in the state of the computer. An example
of this is the expression statement "x++;", which has the
side effect of adding 1 to the value of x. Similarly,
the function call "TextIO.getln()",
which reads a line of input, can be used as a stand-alone
statement if you want to read a line of input and discard it.
Note that, technically, assignment statements and subroutine call
statements are also considered to be expression statements.
Java statement types:
- declaration statement (for declaring variables)
- assignment statement
- subroutine call statement (including input/output routines)
- other expression statement (such as "x++;")
- empty statement
- block statement
- while statement
- do..while statement
- if statement
- for statement
- switch statement
- break statement (found in loops and switch statements only)
- continue statement (found in loops only)
- return statement (found in subroutine definitions only)
- try..catch statement
- throw statement
- synchronized statement