The switch statement
● The switch statement provides a way to execute different sections of code
based on the value of a single expression.
● It is a control statement that allows a program to perform different actions
based on different cases or conditions.
● The basic syntax of a switch statement in Java is as follows:
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
}
● Here, expression is a variable or expression whose value is compared to the
values specified in the cases.
● Each case specifies a value to compare to, and if the value of the expression
matches a case value, the code block following that case is executed.
● If none of the case values match the expression value, the code block
following the default keyword is executed.
● The break statement is used to exit the switch statement after a case is
executed.
● If a break statement is not used, the code will continue to execute the code
block for the subsequent cases until a break statement is encountered or the
end of the switch statement is reached.
● Consider this example of a switch statement that checks the value of a
variable dayOfWeek and executes different code depending on the value:
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".