Skip Top Navigation Bar

Switch Statement and Expressions Lesson Plan

Overview

In this lesson, students will learn how to utilize switch statements and switch expressions.

Learning Objectives

Skills

Student Outcomes

Students will be able to:

Duration: 2 class periods

Resources

Videos

  </div>

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:

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

AP CSA Scoring and Teaching

Final Word

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:

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);

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.

Example 1: 2024 Free Response Question 1

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:

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.

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