Java switch Statement
🔄 Java switch Statement
The switch statement is used to select one of many code blocks to execute based on a variable’s value.
It is an alternative to long chains of if...else if.
✅ Syntax of switch
📌 Important Notes:
-
The
breakkeyword stops the execution after a matching case. -
If
breakis omitted, execution continues into the next case (fall-through). -
defaultruns if no case matches (optional but recommended).
Example 1: Basic switch
📌 Output:
Example 2: Without break (Fall-Through)
📌 Output:
Example 3: switch with String
📌 Output:
🚀 Example 4: Multiple Case Labels
📌 Output:
🧠 When to Use switch?
Use switch when:
✔️ Expression has many fixed values
✔️ Values are int, byte, short, char, enum, or String
