How to use switch
Write a switch statement
Each case matches a possible value. break prevents execution from falling through to the next case.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Unknown day");
}
Group cases
Several labels can share one body when they should produce the same result.
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
System.out.println("Pass");
break;
default:
System.out.println("Keep practicing");
}
Use a switch expression
Modern Java switch expressions use arrow labels, do not fall through, and return a value.
int day = 6;
String kind = switch (day) {
case 1, 2, 3, 4, 5 -> "weekday";
case 6, 7 -> "weekend";
default -> "invalid";
};
Choose switch appropriately
Use switch for a fixed set of exact values. Use if/else for ranges or unrelated boolean conditions.