Syntax
switch(VARIABLE) {
case MATCH_1 [, MATCH_2][, MATCH_N] -> EXPRESSION; | THROW-STATEMENT; | BLOCK
default -> EXPRESSION; | THROW-STATEMENT; | BLOCK
}
Token |
Description |
VARIABLE |
The variable to test. |
MATCH_1, MATCH_2, MATCH_N |
The value or values that can match the VARIABLE. |
EXPRESSION |
A expression to execute. |
THROW-STATEMENT |
A expression that throws an exception. |
BLOCK |
A block of statements to execute.
If a return value is required use the yield keyword instead of return. |
Example
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
Day day = Day.WEDNESDAY;
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> {
System.out.println(8);
yield 8;
}
case WEDNESDAY -> {
System.out.println(9);
yield 9;
}
default -> {
throw new IllegalStateException("Invalid day: " + day);
}
};
System.out.println(numLetters);
Recent Comments