Switch Statements
What are switch statements used for?
- Switch statements are often used when you have a menu of options to choose from.
- Algorithms that use switch statements can also be written with a series of nested if..else statements.
- Using switch statements instead of a series of nested if..else statements can make code more readable.
- Default statements are often required to ensure that all cases are addressed, and the switch is exhaustive.
Basic Structure of a Switch Statement
Sometimes multiple case values have the same action associated with it. At these times, you can put a comma between the two cases as follows:
Example 1: Training
Consider the following code segment which assigns students in an organization to a specific training session based on which weeks they can volunteer. Students who can volunteer in weeks 1 and 2, will attend training 1; week 3 will attend training 2; week 4 will attend training 3; and all other weeks will attend training 4.
Your Turn
Let's try it in the Java Playground.
- Re-written using a switch statement.
- use the keyword
switchfollowed by the variable that you want to check the cases against. - In the body of the switch, there are a series of case statements.
- Each case value is followed by the
->operator and what statements to do for that case. - The arrow symbol
->is used in switch statements and prevents fall through. This means that once a case statement matches, no other statements will be executed. - If the values for a case matches the value of the variable, then the statements associated with that case are executed.
- use the keyword
- The re-write is started below.
- Predict the output of the code.
- Run the code to determine if your prediction is correct or not. Modify the
weekSelectedto have the values 2, 3, and 4 and run each one. - Add the additional cases that to print
Attend training 2andAttend training 2for these weeks as well.
Example 2: Calling Methods
Consider a class called Calculator that has methods to calculate the sum and positive difference of two values as follows:
Based on a string input of + for sum and +- for positive difference, we can call the appropriate method using the conditional operator:
Expanding on this example, assume Calculator has product and quotient methods as well, the code would be:
This code could also be re-written as an if..else statement as follows:
Your Turn
Let's try it in the Java Playground
- The
Calculatorclass is provided for you. - Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Modify the conditional operator expression to use a switch statement instead.
- Test you code with different
x,y, andinputvalues.
Resources
Calculator - Using Conditionals and Lambda Mini-Lab