Lesson 4 of 512 minModule progress 0%

Module 4: Decision Making

`switch` Statements

Use `switch` when you need to pick one path from a small set of known values such as menu choices or days of the week.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-16

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, edited by hand, and checked against current Java 25 documentation and runnable examples.

Learning goals

  • Read and write a basic `switch` statement
  • Use `case` labels and `default`
  • Recognize when `switch` is clearer than an `else if` chain

Why this matters: switch can be cleaner than a long else if chain when you are comparing one variable against a fixed set of values.

The key pieces: A switch has an expression, several case branches, and usually a default branch for anything unmatched.

Use cases: Menu choices, small status values, days, grades entered as letters, and similar fixed options.

Keep it simple: If the logic depends on ranges like score >= 80, switch is usually not the right tool for that job.

Runnable examples

A day-of-week example

public class Main {
    public static void main(String[] args) {
        int day = 2;

        switch (day) {
            case 1 -> System.out.println("Monday");
            case 2 -> System.out.println("Tuesday");
            default -> System.out.println("Unknown day");
        }
    }
}

Expected output

Tuesday

A menu choice

public class Main {
    public static void main(String[] args) {
        char choice = 'B';

        switch (choice) {
            case 'A' -> System.out.println("Account");
            case 'B' -> System.out.println("Billing");
            default -> System.out.println("Help");
        }
    }
}

Expected output

Billing

Common mistakes

Using `switch` for range checks like score bands

Use `if` / `else if` for ranges and `switch` for fixed exact values.

Mini exercise

Create a `switch` for values 1, 2, and 3 that prints three different messages.

Summary

  • `switch` is good for exact known cases.
  • `default` is the fallback branch.

Next step

Finish the module by validating input before the program keeps going.

Sources used

Advertisement

Lesson check

When is `switch` usually a better fit than `else if`?

Next lesson →