The switch statement in Java allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. The break statement is used to terminate a switch block.
Switch-Case in Java
Switch-Case Syntax:
switch(expression) {
case value1: code block; break;
case value2: code block; break;
default: code block; break;
}
Key Points:
The break statement is used to exit the switch block.
If no break is used, the next case is executed (fall-through behavior).
The default case is optional and runs if no case matches.
Program Example
Input:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
// Switch statement with break
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day: " + dayName);
}
}