The switch statement in Java is a control flow statement that allows you to execute different blocks of code based on the value of a variable or expression. It is often used as a cleaner and more readable alternative to multiple if-else conditions.
case labelsbreak to stop executiondefault runs when no case matchesint, char, String, and enum
// General syntax of Java switch statement
switch(expression) {
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
// Java program demonstrating switch statement
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;
case 4:
System.out.println("Thursday");
break;
default:
System.out.println("Invalid day");
}
The value of day is 3, so the control jumps to case 3 and prints Wednesday. The break statement stops further execution.
break to avoid fall-throughdefault to handle unexpected valuesswitch when checking one variable against many valuesString values inside a switchbreak and observe fall-through behaviorif-else ladder using switch