The general form of a switch statement looks like this:
switch (expression) { case const1: code case const2: code case const3: code default: code } |
The expression:
- A switch's expression must evaluate to values that can implicitly cast to an int - in other words char, byte, short, int and enum. This means it can be a call to a function as long as the function return the right value.
- It can only check for equality, that is not greater than or less than or something like that.
- Boxing is allowed. See example 1.1.
Cases:
- Case constants are evaluated from top and down. The first case that matches the expression is the entry point in the switch clause. After entering, execution will continue for each subsequent case statement unless there is a break (see below).
- The case constant (for example const1 above), must evaluate to the same type as the switch expression can use and it has to be a compile-time constant (see below).
- There can not be more than one label using the same value. See example 1.2 which is illegal.
- The special case "default" can be used for the cases when there are no match.
The break statement:
The keyword "break" can be inserted at the end of each code block for each case statement, After entering some case statement that code block will run. If it ends with a "break", execution will immediately move out of the switch block. If there is no "break", execution will continue for each case statement until a break is found or until the end of the switch clause, this is referred to as
fall-through. See example 1.3 for a simple example that uses "break".
Compile-time constant:
The definition from is:
A compile-time constant expression is an expression denoting a value of primitive type or null or a String that is composed using only the following:
Literals of primitive type, null and literals of type String |
So for the case of a switch clause, the compile-time constant is an int or a type that can be implicitly cast to an int and that can be resolved at compile time, which means that a case constant can only be a constant or a final variable that is assigned a literal int value.
Example 1.1:
switch (new Integer(2)) { case 2: System.out.println("This works!"); } |
Example 1.2:
switch (x) { case 2: System.out.println("2"); case 2: System.out.println("2"); case 3: System.out.println("3"); default: System.out.println("default"); } |
Example 1.3:
switch (x) { case 1: System.out.println("1"); break; case 2: System.out.println("2"); break; case 3: System.out.println("3"); break; default: System.out.println("default"); break; } |