Java switch Statement Syntax
The switch keyword takes an expression in parentheses. Each case label holds one value to compare with it, and the default label catches every other value.
How does the switch statement work in Java?
The switch statement evaluates the expression and runs the statements after the matching case label. A break statement ends the switch. Without break, execution falls through to the statements of the next case. The default section runs when no case label matches.
A switch works with byte, short, char and int values, their wrapper classes Byte, Short, Character and Integer, enum types and String.
Java Switch Statement Examples
The following are examples of the switch statement in Java. Run them in the online Java code runner to see which case matches.
Switch on an int value
The switch compares the int with each case label and stops at the first break.
Switch on a String
A String in a switch is compared with each case label as if by the equals() method, so the comparison is case-sensitive.
Several case labels for one block
To run the same code for several values, list their case labels one after another before the code. Here months 4, 6, 9 and 11 share one block.
Switch expression with case -> labels
A switch can also be used as an expression, for example on the right side of an assignment. A switch expression always evaluates to one value: the value to the right of the matching arrow. Arrow labels do not fall through, so no break is needed, and one case can list several values separated by commas. A switch expression must cover every possible value, so it usually ends with default.