Skip to Content
Course content

13: Control Flow: Switch Statements

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're standing in front of a vending machine. You don't look at every single item in the machine and ask yourself, "Is this a bag of chips? No. Is this a granola bar? No. Is this a soda? Yes!" That would be an incredibly slow way to get a snack. Instead, you just punch in a code—say, B4—and the machine jumps directly to that specific slot to dispense your item.

That's exactly what a switch statement does for your code. While an if-else if chain is like checking every item one by one, a switch is like the vending machine. It takes one value and jumps straight to the "case" that matches it. It's cleaner, faster to read, and tells anyone looking at your code: "I am picking one option from a predefined list."

Choosing the right path

Let's look at a practical example. Suppose you're building a basic customer support menu for a phone system. You want to route the caller based on the number they press.

int userChoice = 2;

switch (userChoice) {
    case 1:
        System.out.println("Routing to Sales...");
        break;
    case 2:
        System.out.println("Routing to Technical Support...");
        break;
    case 3:
        System.out.println("Routing to Billing...");
        break;
    default:
        System.out.println("Invalid choice. Please try again.");
        break;
}

Here is how the vending machine analogy maps to this code:

  • The Code (userChoice): This is the button the user pressed. It's the single value the switch is evaluating.
  • The Cases (case 1, 2, 3): These are the slots in the machine. If userChoice is 2, Java skips cases 1 and jumps straight to case 2.
  • The Default: This is the "Invalid Entry" light on the machine. If the user presses 9, but you only have 3 options, the default block catches everything else.

The "Fall-Through" Trap

I have to warn you about the break statement. In the example above, break tells Java, "Okay, we're done here; jump out of the switch entirely." If you forget it, Java does something called "falling through." It will keep executing the code in the next case, regardless of whether the value matches, until it hits a break or the end of the statement.

Usually, falling through is a bug that will keep you up until 2 AM wondering why your "Sales" call is also triggering "Technical Support" and "Billing" messages. However, you can actually use this on purpose if multiple inputs should trigger the same result:

String day = "Saturday";

switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        System.out.println("It's a workday.");
        break;
    case "Saturday":
    case "Sunday":
        System.out.println("It's the weekend!");
        break;
}

Modernizing with Switch Expressions

If you're using a recent version of Java (Java 12 or later), you'll see a much sleeker syntax using arrows (->). I personally prefer this because it eliminates the need for break entirely—no more fall-through bugs. It can even return a value directly into a variable.

String day = "Monday";

String typeOfDay = switch (day) {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Workday";
    case "Saturday", "Sunday" -> "Weekend";
    default -> "Unknown day";
};

System.out.println(typeOfDay);

Notice the comma-separated lists and the lack of break. It's concise, readable, and much harder to mess up. When you're writing your own code, use this version if your project environment allows it.




📋 Practical Task

Build a Simple ATM Menu Handler

Your task is to create a program that simulates a basic ATM interface. The program should take an integer input representing a user's menu choice and print the corresponding action.

Requirements:

  • Create an integer variable named menuChoice.
  • Implement a switch statement (either the traditional version or the modern expression version) that handles the following:
    • 1: Print "Checking Balance..."
    • 2: Print "Depositing Funds..."
    • 3: Print "Withdrawing Funds..."
    • 4: Print "Changing PIN..."
    • Any other number: Print "Error: Selection not recognized."
  • Ensure that if the user selects 1, it does not also print the messages for 2, 3, or 4.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.