Control Structures
2. Switch Statement
Selects one of many code blocks to execute based on the value of an expression (typically an int, char, String, or enum).
Syntax (Java 7+ for String):
switch (expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code if no case matches
}
Example:
public class SwitchExample {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("Start of the week"); // Output: Start of the week
break;
case "Friday":
System.out.println("End of the work week");
break;
default:
System.out.println("Midweek or weekend");
}
}
}