Switch: The Efficient Menu

Switch: The Efficient Menu in Java: If is a fork in the road, is an Elevator Panel. Instead of checking "Is it floor 1? Is it floor 2? Is it floor 3?" you just…

Concept Explanation

If if-else is a fork in the road, switch is an Elevator Panel. Instead of checking "Is it floor 1? Is it floor 2? Is it floor 3?" you just press the button for the floor you want and go directly there.

It's much faster and cleaner when you have many specific options (like days of the week or menu items).


Syntax or Core Structure

int day = 3;
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("Other day");
}

The 'break' keyword

Crucial! If you forget break, Java will keep running the code for the next cases even if they don't match. This is called "Fall-through."


Best Practices

  • Always include a 'default': It's the "Catch-all" for when none of the cases match.
  • Modern Switch (Java 14+): Research "Switch Expressions" (yield and arrows ->) which make switch statements much more powerful.
  • Use for Enums: Switch works perfectly with Enum types (like Color.RED).

Practice Exercises

  1. The Month Name: Write a switch statement that converts a number (1-12) into a Month name.
  2. The Calculator: Use a switch statement to perform +, -, *, or / based on a char operator variable.
  3. The Fall-through: Write a switch statement for "Workdays vs Weekends" where cases 1-5 all do the same thing by intentionally omitting break.