Careeroza
Classic switch Statement
Syntax
switch compares one value against many case labels. It is cleaner than a long else if chain when you test the same variable for exact values.
Example
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Another day");
}
}
}Output
Wednesday
Fall-through
Example
Without break, execution "falls through" into the next case. This is a common bug, but it is also used on purpose to group cases.
public class Main {
public static void main(String[] args) {
int level = 2;
System.out.println("Unlocked features:");
switch (level) {
case 3:
System.out.println(" - priority support");
case 2:
System.out.println(" - free delivery");
case 1:
System.out.println(" - order tracking");
}
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
System.out.println("Good job");
break;
case 'C':
System.out.println("You passed");
break;
default:
System.out.println("Work harder");
}
}
}Output
Unlocked features: - free delivery - order tracking Good job
Rules
- Allowed types:
byte,short,char,int, their wrappers,Stringand enums (and any type with pattern matching in Java 21). - Not allowed in a classic switch:
long,float,double,boolean. - Case labels must be constants and unique.
defaultis optional and runs when nothing matches.