Curriculum
In Java, the switch statement is used to perform different actions based on different conditions. It is often used as an alternative to a series of if-else statements.
The basic syntax for a switch statement is:
switch (expression) { case value1: // code block 1 break; case value2: // code block 2 break; // more cases can be added here default: // default code block }
In this syntax, “expression” is any expression that can be evaluated to an integer, a character, or a string. The switch statement evaluates the expression and then compares it to each of the cases. If a case matches the value of the expression, then the code block for that case is executed. If there is no match, then the code block for the default case is executed.
Here’s an example of a switch statement in action:
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; default: dayName = "Weekend"; } System.out.println("Today is " + dayName);
In this example, the value of “day” is 3, so the case “3” matches the value of the expression. Therefore, the code block for case “3” is executed, and the value “Wednesday” is assigned to the variable “dayName”. Finally, the message “Today is Wednesday” is printed to the console.
Note that the “break” statement is used to terminate the switch statement for the matching case. Without the “break” statement, the switch statement would continue to execute the code for all cases below the matching case, which is known as “falling through” the cases.
When using a switch statement in Java, there are several rules that must be followed: