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
javaswitch (variable) { case value1: // code break; case value2: // code break; default: // code if nothing matches }
5. Example Program
javapublic 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:
Wednesday6. Key Points to Remember
- Forgetting
breakcauses "fall-through," where execution continues into the next case unintentionally. defaultis 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.