next up previous
Next: Omission of break (optional) Up: Unit 05 Previous: Example of switch statement

Observation on the switch statement

The expression used for the selection can be an arbitrary Java expression that returns an integer or character value (but not a floating point value).

The values specified by the various case labels must be constant expressions, i.e., their value must be known at compile time. In particular, they cannot be expressions that refer to variables.

The following code fragment is wrong:

int a;
...
switch (a) {
  case a<0: System.out.println("negative");
                                 // ERROR!  a<0 is not a constant expression
  case 0:   System.out.println("zero");
  case a>0: System.out.println("positive");
                                 // ERROR!  a>0 is not a constant expression
}

It follows that the usefulness of the switch statement is limited.


next up previous
Next: Omission of break (optional) Up: Unit 05 Previous: Example of switch statement