Thuta Learning
BasicProgrammingbeginner

Switch

Relax. We'll talk through this in plain words — no textbook voice.

switch compares a value against several cases and runs the matching block. When you'd otherwise need a long chain of if/else statements, switch can make things cleaner. It's handy for checking fixed values like a menu option, day number, user role, or status code.

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

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

day is 4, so it matches case 4 and prints Thursday. break is used to exit the switch after the selected case runs.

You should see
Thursday

Real-world use

The switch pattern can be used for things like dashboard tab selection, order status handling, role-based menu display, and command-line menu systems.

Easy traps

  • Forgetting break is the classic switch bug—execution can fall through into the cases below.