Lesson: SWITCH Statement

Explore program flow control using the SWITCH statement.

Understand how to employ comparisons to alter program flow with the SWITCH statement.


The switch statement allows you to compare a value to a list of possible matching values and so select from multiple possible statements or blocks. A key difference from the if statement is that the value compared is not boolean, but instead numeric, enumeration (discussed later) or String. The form of the switch statement is:

This basic form of switch evaluates an expression resulting in a numeric value. That value is checked against the case statement values and if there is a match, the statement(s) following the case are executed. Note that execution continues into the following case statements unless the list of statements to execute is terminated by a break statement. The break statement ends a case block and execution continues with the first statement after the switch block. Most of the time each case will end with a break but there may be situations where you want case 2 executed in addition to case 1 (for example). If no case statement is matched, the default case is executed (if present). Here is an example switch block:

With x = 2, the second case is executed and execution stops with the break resulting in z = 5. If x = 1, then the first case is executed, setting z = 1, and the second case would also be executed (no break after first case) setting z = 5 and then ending there. If x = 3, then the third case and the default case (no break after third case) would be executed and z would be = 11 at the end of the execution. If x = 5, no case is matched so the default case would be executed and z would = 11. Here is the example code in CodingGround. Try changing the value of x as discussed here and prove that it works. Modify the code so that setting x = 3 results in z = 9.
There is a use-case where you have multiple case statements in a row with no intervening code:

Here we want to call method doSomething() if foo is 0 or 1.
Using Strings with switch statements is similar. Assuming day is a String variable = "tuesday", here is an example:

In this example, dayNumber will  be 2 after the switch is done. Using enumerations on switch statements is another powerful form but will be discussed in a later section.

Here is a video about switch. Here is a detailed discussion of switch. Here is this example in CodingGround. Complete and test the example in CodingGround for the full 7 days of the week.

In robotics, switch can be useful to match information from controllers and sensors that is numeric in nature to actions to be taken. For instance, joysticks may return which button is pressed as a numeric value. A switch statement can match the button numbers to actions.