Control Statements
if/else and switch
switch
The syntax of the switch statement
switch (integerExpression) { case label1: statements break; case label2: statements break; any other case statements default: (optional) statements break; }
How to code switch statements
- The switch statement can only be used with an expression that evaluates to one of these integer types: char, byte, short, or int.
- The case labels represent the integer values of the expression, and these labels can be coded in any sequence.
- The switch statement transfers control to the appropriate case label.
- If control isn't transferred to one of the case labels, the optional default label is executed.
- If a case label doesn't contain a break statement, code execution will fall through to the next label. Otherwise, the break statement ends the switch statement.
A switch statement with a default label
switch (productID) { case 1: productDescription = "Hammer"; break; case 2: productDescription = "Box of Nails"; break; default: productDescription = "Product not found"; break; }
A switch statement that falls through case labels
switch (dayOfWeek) { case 2: case 3: case 4: case 5: case 6: day = "weekday"; break; case 1: case 7: day = "weekend"; break; }