Switch

Switch

A school program needs reliable data and clear rules. A switch selects an action from labeled values. The school can map a day number to a message without writing several equality checks.

  1. Understand

    A switch selects an action from labeled values.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Traditional colon-style cases can fall through without break. Arrow-style cases have different syntax and do not fall through.

Switch Statement in Java

When you're faced with multiple paths of logic based on the value of a single variable, the switch statement in Java shines as a clean, readable alternative to a long series of if-else-if blocks. It helps you route your program's behavior based on specific values—like menu choices, user input, or predefined constants.

Why Use a Switch Statement?

Imagine choosing what to eat at a food court. Based on the stall number, you want to print out the food item. You can use an if-statement and write:

import java.util.Scanner;

class FoodStallSelector {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // Create Scanner object to take input

        System.out.println("Enter your stall number (1 for Pizza, 2 for Burger, 3 for Sushi):");
        int stall = sc.nextInt(); // Read the stall number entered by the user

        // Conditional logic to choose food item based on stall number
        if (stall == 1) {
            System.out.println("Pizza");
        } else if (stall == 2) {
            System.out.println("Burger");
        } else if (stall == 3) {
            System.out.println("Sushi");
        } else {
            System.out.println("Option not available");
        }

        sc.close(); // Close the scanner
    }
}
Enter your stall number (1 for Pizza, 2 for Burger, 3 for Sushi):
2
Burger

Or you could write this more cleanly using switch:

import java.util.Scanner;

class FoodStallMenu {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // Create a Scanner object for user input

        System.out.println("Enter your stall number (1 for Pizza, 2 for Burger, 3 for Sushi):");
        int stall = sc.nextInt(); // Read the stall number entered by the user

        // Switch statement to display selected stall's item
        switch (stall) {
            case 1:
                System.out.println("Pizza");
                break;
            case 2:
                System.out.println("Burger");
                break;
            case 3:
                System.out.println("Sushi");
                break;
            default:
                System.out.println("Option not available");
        }

        sc.close(); // Close the scanner
    }
}
Enter your stall number (1 for Pizza, 2 for Burger, 3 for Sushi):
2
Burger

Java Switch Statement Syntax

switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    ...
    default:
        // default code block
}

Flow diagram: key actions and decisions

  1. Start
  2. Evaluate expression
  3. case value1?
  4. code block 1
  5. break
  6. End
  7. case value2?
  8. code block 2
  9. default present?
  10. default block

These labels identify the actions and decisions in the original diagram; the list does not represent branch order. Follow the Java code for the exact execution path.

Key Points:

  • The expression must evaluate to int, char, byte, short, enum, or from Java 7 onwards, String.
  • The break statement is used to terminate a case. Without it, execution "falls through" to the next case.
  • The default case is optional and executes when none of the cases match.

Basic Example with Integers

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

        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}
Tuesday

Fall-Through Behavior

If you omit break, Java continues to execute the next statements—even if the case matched!

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

        switch (choice) {
            case 1:
                System.out.println("First");
            case 2:
                System.out.println("Second");
            case 3:
                System.out.println("Third");
        }
    }
}
Second
Third

This is known as fall-through, and while sometimes useful, it can also lead to bugs if not handled carefully.

Switch with Strings (Java 7+)

Starting from Java 7, you can use String values in a switch statement — not just numbers or characters.

In this example, the program checks the value of the fruit variable. If it matches one of the defined case labels, like "Apple" or "Banana", it runs the matching code block. If none match, it runs the default block.

Switching on strings makes your code cleaner and easier to understand when working with text-based conditions.

class FruitColor {
    public static void main(String[] args) {
        String fruit = "Apple";

        switch (fruit) {
            case "Apple":
                System.out.println("Red fruit");
                break;
            case "Banana":
                System.out.println("Yellow fruit");
                break;
            default:
                System.out.println("Unknown fruit");
        }
    }
}
Red fruit

Switch Expressions (Java 14+)

Modern Java versions allow switch expressions that return values:

This example uses a switch expression, a newer way to use switch in Java 14 and above. Unlike the traditional switch statement, a switch expression can directly return a value, making the code shorter and easier to understand.

In this code, the variable day is checked. If it's 1, it returns "Monday"; if it's 2, it returns "Tuesday"; and so on. The result is then stored in the result variable and printed. This style removes the need for break statements and makes the code cleaner.

class DaySwitchExample {
    public static void main(String[] args) {
        int day = 2;  // You can change this value to test other cases

        String result = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            default -> "Invalid";
        };

        System.out.println("The day is: " + result);
    }
}
The day is: Tuesday

Nested Switch Statements

In Java, a nested switch statement means placing one switch statement inside another. This is useful when you need to make decisions based on multiple related values.

In the following example, we have two variables: section and shelf. First, the outer switch checks the value of section. If it matches 1, the program then enters another switch to check the value of shelf. Based on the combination, it prints out a message showing the exact section and shelf.

class LibraryLayout {
    public static void main(String[] args) {
        int section = 1;
        int shelf = 2;

        switch (section) {
            case 1:
                switch (shelf) {
                    case 1:
                        System.out.println("Section 1 - Shelf 1");
                        break;
                    case 2:
                        System.out.println("Section 1 - Shelf 2");
                        break;
                    default:
                        System.out.println("Section 1 - Unknown Shelf");
                }
                break;
            case 2:
                System.out.println("Section 2");
                break;
            default:
                System.out.println("Unknown Section");
        }
    }
}
Section 1 - Shelf 2

Best Practices and Gotchas

  • Always use break unless you're intentionally falling through.
  • Use default to handle unexpected inputs.
  • Be cautious with variable types—switch expressions need exact matches.
  • Prefer switch for fixed values; use if-else for range checks.

Real-Life Example: Menu Selection

This program shows a simple real-life example of using a menu with numbers to control actions. The user is asked to enter a number (1, 2, or 3) to start, stop, or exit a system.

The program uses a Scanner to take input from the user, and then a switch statement to decide what message to show based on the user's choice. This kind of logic is useful in real applications like ATMs, vending machines, or menu-driven programs.

import java.util.Scanner;

class SystemControl {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // Create Scanner object for input

        System.out.println("Enter your choice: 1. Start 2. Stop 3. Exit");
        int input = sc.nextInt(); // Read integer input

        // Use enhanced switch statement (Java 14+)
        switch (input) {
            case 1 -> System.out.println("System Started...");
            case 2 -> System.out.println("System Stopped.");
            case 3 -> System.out.println("Exiting System.");
            default -> System.out.println("Invalid choice.");
        }

        sc.close(); // Close the scanner
    }
}
Enter your choice: 1. Start 2. Stop 3. Exit
1
System Started...

Important boundaries and mistakes

Traditional colon-style cases can fall through without break. Arrow-style cases have different syntax and do not fall through.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Traditional colon-style cases can fall through without break.

Java 17 · Main.java · complete practice program

public class Main  {
  public static void main(String[] args)  {
    int day = 2;
    switch (day)  {
      case 1: System.out.println("Maths");
      break;
      case 2: System.out.println("Science");
      break;
      default: System.out.println("No class");
    }
  }
}

Now change one thing: Change day to 1. Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  public static void main(String[] args)  {
    int day = 2;
    switch (day)  {
      case 1: System.out.println("Maths");
      break;
      case 2: System.out.println("Science");
      break;
      default: System.out.println("No class");
    }
  }
}

Expected output

Science

A switch selects an action from labeled values. The school can map a day number to a message without writing several equality checks.

Traditional colon-style cases can fall through without break. Arrow-style cases have different syntax and do not fall through.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Worked variation: Change day to 1. The selected case prints Maths and its break exits the switch.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Science

A switch selects an action from labeled values. The school can map a day number to a message without writing several equality checks. Traditional colon-style cases can fall through without break. Arrow-style cases have different syntax and do not fall through.

What to remember

A switch selects an action from labeled values. The school can map a day number to a message without writing several equality checks. Traditional colon-style cases can fall through without break. Arrow-style cases have different syntax and do not fall through.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Ternary Operator →