Java Language Reference

Previous Chapter 6
Statements and Control Structures
Next
 

6.6 The switch Statement

A switch statement selects a specially labeled statement in its block as the next statement to be executed, based on the value of an expression:

[Graphic: Figure from the text]

In Java, the type of the expression in parentheses must be byte, char, short, or int. This is unlike C/C++, which allows the type of a switch statement to be any integer type, including long.

The body of a switch statement must be a block. The top-level statements inside a switch may contain case labels. The expression following a case label must be a constant expression that is assignable to the type of the switch expression. No two case labels in a switch can contain the same value. At most one of the top-level statements in a switch can contain a default label.

A switch statement does the following:

Here's an example of a switch statement:

switch (rc) {
  case 1:
    msg = "Syntax error";
    break;
  case 2:
    msg = "Undefined variable";
    break;
  default:
    msg = "Unknown error";
    break;
}

After the switch statement has transferred control to a case-labeled statement, statements are executed sequentially in the normal manner. Any case labels and the default label have no further effect on the flow of control. If no statement inside the block alters the flow of control, each statement is executed in sequence with control flowing past each case label and out the bottom of the block. The following example illustrates this behavior:

void doInNTimes(int n){
    switch (n > 5 ? 5 : n) {
      case 5:
        doIt();
      case 4:
        doIt();
      case 3:
        doIt();
      case 2:
        doIt();
      case 1:
        doIt();
    }
}

The above method calls the doIt() method up to 5 times.

To prevent control from flowing through case labels, it is common to end each case with a flow-altering statement such as a break statement. Other statements used for this purpose include the continue statement and the return statement.

References Constant Expressions; Expression 4; Identifiers; Integer types; Local Classes; Local Variables; Statement 6; The break Statement; The continue Statement; The return Statement


Previous Home Next
The if Statement Book Index Iteration Statements

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java
This HTML Help has been published using the chm2web software.