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
