In Java, the switch statement is another way to control the flow of a program based on the value of an expression.
It provides a more concise alternative to multiple if-else statements when we have multiple conditions to check against the same value.
The switch statement evaluates the expression and then executes the code block corresponding to the matching case label.
Here's the basic syntax of the switch statement:
switch (expression) { case value1: // code to be executed if expression equals value1 break; case value2: // code to be executed if expression equals value2 break; // more case labels can be added as needed default: // code to be executed if expression does not match any case label }
The "expression" is evaluated once and compared against the values of each "case" label.
If a match is found, the corresponding block of code is executed.
The "break" statement is used to exit the "switch" block after executing the code for the matching case. Without a "break", control will fall through to the next case, executing its code as well.
The "default" case is optional and is executed if no match is found between the expression and any of the case labels.
class SwitchStatement { public static void main(String[] args) { int day = 3; String dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } System.out.println("The day is " + dayName); } }
The day is Wednesday
If day is equal to 3, the variable dayName will be assigned the value "Wednesday".
If day is equal to any other value, the default case will be executed, and dayName will be assigned the value "Invalid day".
The switch statement is particularly useful when we have a single expression with multiple possible values and want to execute different blocks of code based on those values.