Switch Statement and Expressions Lesson Plan
Overview
In this lesson, students will learn how to utilize switch statements and switch expressions.
Learning Objectives
- 1.2.B.4 Write and interpret
switch
statements and expressions.
Skills
- S2.A Write program code and implement algorithms.
- S2.C Analyze an algorithm and program code for correctness.
Student Outcomes
Students will be able to:
- use switch statements and expressions without lambda expressions in a program
- use switch statements and expressions with lambda notation in a program
Duration: 2 class periods
Resources
Videos
Warm-up / Motivate - Day 1
Have students work in pairs to expand the if statement that could be used to determine the cost of the an item ordered at an ice cream shop based on whether the item is ice cream or sorbet. An ice cream shop now has 5 options for customers:
- option 1 - ice cream: $5
- option 2 - sorbet: $6
- option 3 - frozen yogurt: $5.50
- option 4 - sherbert: $5.75
- option 5 - mixer: $7
There are many ways that students can choose to solve this problem. Here's one option:
int options = 1;
double cost = 0;
if (options == 1) {
cost = 5;
} else {
if (options == 2) {
cost = 6;
} else {
if (options == 3) {
cost = 5.5;
} else {
if (options == 4) {
cost = 5.75;
} else {
if (options == 5) {
cost = 7;
} else {
cost = 0;
}
}
}
}
}
As you can see this can get really long and involved. It becomes less readable as more options are added. It's also a lot easier for you to make small coding mistakes, like not matching braces. Using a switch statement is a better option for this type of problem.
Learn
Practice
Either have students record their practice to collect and provide feedback or review the practice as a whole group.
Learn
Apply
Complete the following mini-lab: Apply: Conditional and Lambda Mini-Lab
Wrap-up / Extension
Have students revisit some of the programming projects or exercises that they completed with if..statements and determine which could be re-written using the switch statements or expressions. For those where a student would not recommend using the switch statements or expressions instead, have them justify this decision.
Switch Statements and AP CSA FRQs
- Switch statements are OUTSIDE the AP CSA Java Subset.
- Students can write correct solutions using switch statements.
- Switch statements can be used in any FRQ, but may be seen more often in Question 1.
AP CSA Scoring and Teaching
- Student solutions that use correct Java syntax can earn full credit for their solution
- Questions are written with an in AP Java subset solution in mind
- Students should be encouraged to write solutions within the AP Java Subset
Final Word
- Switch statements are often used when there is a menu of options to respond to.
- Switch statements are often more readable than using equivalent nested if statements.
- Use
break;
or lambda notation (->
) to prevent fall through in a switch statement.
What's Next for Switch Statements and Switch Expressions?
Previewing in JDK 24, Primitive Types in Patterns, instanceof, and switch.
NOTE: Preview features are not guaranteed to be released. Potential new features are proposed openly in the community via a document called a JDK Enhancement Proposal or JEP.
Each JEP goes through the following lifecycle:
- Each must be approved for inclusion with a target release.
- Each goes through at least 1 preview cycle to address feedback. Most go through 2-3 previews but it could be more.
- Once feedback is addressed and the community approves the implementation, the JEP is targeted for a release as a final candidate.
- With each release revision, the proposal documentation is updated to reflect the current state of the proposal and it is given a new identifying number to ensure traceability through history on versions of the idea.
JEP 488: Primitive Types in Patterns, instanceof, and switch
For instanceof
– allows the use of instanceof
with primitive types instead of just reference types. It checks whether a variable can be represented by a specific type without any loss of precision of data.
For switch - allows for the use of a switch over all primitive types.
To ensure all cases are being covered, we can add guards to our switch expressions.
int x = -1; //change the value of x for other outputs
String result = switch (x){
case 0 -> "zero";
case int y when y < 0 -> "negative";
case int z -> "positive";
}
System.out.println (result);
when
is being used as a condition
- The third case is for anything that isn’t the first two
- No default is required, the third case acts as the default
Other Primitive Data Types for Switch
Currently, we can not use a switch for boolean variables. This new feature would allow for the following:
int x = 12; //change the value of x for other outputs
String result = switch(x % 2 == 0) {
case true -> "Even";
case false -> "Odd";
}
System.out.println (result);
Or if you wanted to report out the information, use a switch statement:
int x = 11; //change the value of x for other outputs
switch(x % 2 == 0) {
case true -> System.out.println ("Even");
case false -> System.out.println ("Odd");
}
Switch Expressions and the AP CSA Free Response Exam
If you are an AP CSA teacher, please remember that switch statements and switch expressions are OUTSIDE the AP CSA Java subset. Therefore, this topic does not need to be taught to students and might be best left for after the AP exam or a post-AP type course.
In 2024, question 1 can be re-written using the ternary conditional operator. The full question and solution can be found here.
To summarize, this question has a class called Feeder
that has an instance variable currentFood
and two methods simulateOneDay
and simulateManyDays
. Students are asked to implement these two methods. We are looking at writing the simulateOneDay
method.
To simulate a day at the bird feeder, students will need to do the following:
- generate a random number to determine if a bear visited the bird feeder.
- If a bear came to the feeder, the value of
currentFood
would be set to 0
.
- If there is no bear, then another number is simulate the amount of food each bird will consume.
- If the amount of food the birds consumed exceeds the amount in the feeder, the value of
currentFood
is 0
, otherwise the amount consumed is subtracted from currentFood
.
An example solution is as follows:
In the previous example, I used a boolean
variable bearPresent
and a nested if statement. Unfortunately with JDK 23, we cannot use a switch statement or expression with boolean, so we are using an int
variable bearPresent
instead.
I needed to use a default to cover all cases where bearPresent
wasn't 0
or 1
, which is impossible the way that I wrote it, but the default is necessary anyway.
I could also have used lambda notation as follows:
Preview features Primitive Types in Patterns, instanceof, and switch and AP CSA FRQ
Previewing in JDK 24, Primitive Types in Patterns, instanceof, and switch.
- For switch - allows for the use of a switch over all primitive types.
To ensure all cases are being covered, we can add guards to our switch expressions.
So, if this preview feature becomes incorporated into the Java language allowing us to use boolean variables in switch statements and expressions, I could write the following:
public void simulateOneDay (int numBirds) {
boolean bearPresent = false;
double bear = Math.random() * 100;
if (bear <= 5) {
bearPresent = !bearPresent;
}
int birdConsumed = ((int) (Math.random() * 41) + 10) * numBirds;
currentFood = switch (bearPresent) {
case true:
yield 0;
case false:
yield ((birdConsumed >= currentFood) ? 0 : currentFood - birdConsumed);
};
}
Or if I'm using lambda notation:
public void simulateOneDay (int numBirds) {
boolean bearPresent = false;
double bear = Math.random() * 100;
if (bear <= 5) {
bearPresent = !bearPresent;
}
int birdConsumed = ((int) (Math.random() * 41) + 10) * numBirds;
currentFood = switch (bearPresent) {
case true -> 0;
case false -> ((birdConsumed >= currentFood) ? 0 : currentFood - birdConsumed);
};
}
AP CSA Scoring and Teaching
- Student solutions that use correct Java syntax can earn full credit for their solution
- Questions are written with an in AP Java subset solution in mind
- Students should be encouraged to write solutions within the AP Java Subset