Lecture 13 - The switch statement
Lecture 13 - The switch statement
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
// add more cases as needed
default:
// code to execute if expression doesn't match any case
}
1
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Invalid day of the week");
}
● In this example, if the value of dayOfWeek is 2, the code block following the
second case statement will be executed, which prints the message "Today is
Tuesday" to the console.
● If the value of dayOfWeek is not 1 through 7, the default code block will be
executed, which prints the message "Invalid day of the week".