Skip to content
C

switch

A switch statement checks a single value against multiple possible matching cases and runs the code block for whichever case matches. It's a cleaner alternative to writing many else if checks for a single variable.


1. What is a switch Statement?

A switch statement checks a single value against multiple possible matching cases and runs the code block for whichever case matches. It's a cleaner alternative to writing many else if checks for a single variable.

2. Why is it used?

When a program needs to compare one variable against many fixed possibilities — like a day number, a menu choice, or a grade letter — switch makes the code more organized and often easier to read than a long else-if chain.

3. Real-Life Example

Think of a TV remote's channel selector. Based on the exact channel number pressed, the TV switches to that specific channel. Each channel number is like a case, matched exactly against your input.

4. Syntax

java
switch (variable) { case value1: // code break; case value2: // code break; default: // code if nothing matches }

5. Example Program

java
public class SwitchDemo { public static void main(String[] args) { 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("Invalid day"); } } }

Output:

Wednesday

6. Key Points to Remember

  • Forgetting break causes "fall-through," where execution continues into the next case unintentionally.
  • default is optional but is good practice for handling unexpected values.
  • Modern Java also supports a newer arrow-style switch expression, which avoids the fall-through problem entirely.