Switch Case
Source: Dev.to
What is a switch statement?
The switch keyword in Java is used to execute one block of code among many alternatives. The expression is evaluated once and compared with the values of each case. If the expression matches a case value, the code for that case is executed. If there is no match, the code of the default case is executed.
Syntax
switch (expression) {
case value1:
// statements
break; // optional
case value2:
// statements
break;
// ...
default:
// statements
}
- The
breakstatement terminates theswitch‑casestatement. - If
breakis omitted, execution falls through to subsequent cases.
Allowed types for the expression
byteshortintcharString(since Java 7)
Types not allowed
longfloatdoubleboolean
Default case
The default case is optional. It is used to handle unexpected values when none of the specified cases match.
Example
public class SwitchExample {
public static main(String[] args) {
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done");
break;
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}
}
}
Switch expression syntax in Java 12 and above
Java 12 introduced the arrow (->) syntax for switch expressions, which eliminates the need for explicit break statements.
Example (Java 12)
int day = 1;
switch (day) {
case 1, 7 -> System.out.println("Weekend");
case 2, 3, 4, 5, 6 -> System.out.println("Weekday");
default -> System.out.println("Invalid day");
}