← Chapter 4 — Decision Making & Loops

17. switch Statements

mixed

Description

A switch chooses a branch based on one expression. It is often clearer than a long chain of equality checks for menu options, grades, or known categories.

Modern Java also supports switch expressions, but the classic switch statement is a useful foundation. Include default to handle unexpected values.

Subtopics

Case labels

Description

Each case matches one possible value.

Explanation

break prevents the next case from running unintentionally.

Example

case 'A': System.out.println("Excellent"); break;

Default branch

Description

default handles unmatched input.

Explanation

It keeps a program predictable when data is invalid.

Example

default: System.out.println("Unknown grade");

Explanation

Classic switch statements can fall through to the next case when break is omitted. Fall-through is sometimes intentional, but state that purpose clearly.

Example

public class SwitchDemo {
    public static void main(String[] args) {
        char grade = 'B';
        switch (grade) {
            case 'A': System.out.println("Excellent"); break;
            case 'B': System.out.println("Good work"); break;
            default: System.out.println("Keep learning");
        }
    }
}

Key points

  • switch compares one expression.
  • break prevents accidental fall-through.
  • default handles other values.

Open reference