Switch-case in Java

In Java, the switch-case statement provides a concise way to handle multiple branches of execution based on the value of a variable or an expression. This construct enhances the readability and efficiency of your code, especially when dealing with multiple conditions. In this blog post, we will explore the syntax and usage of the switch-case statement in Java, along with illustrative examples.

switch-case Statement

The switch-case statement evaluates the value of an expression and compares it against multiple case labels. Once a matching case label is found, the corresponding block of code is executed. Here's the syntax of the switch-case statement:

switch (expression) {
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    // add more cases as needed
    default:
        // code to be executed if expression does not match any case
        break;
}
Example
public class SwitchCaseExample {
    public static void main(String[] args) {
        int day = 4;
        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";
                break;
        }

        System.out.println("The day is: " + dayName);
    }
}

In the above example, the switch-case statement is used to determine the name of the day based on the value of the "day" variable. The code evaluates the value of "day" and matches it with the corresponding case label. In this case, since the value of "day" is 4, the case label "4" matches, and the variable "dayName" is assigned the value "Thursday". The output will be: "The day is: Thursday".

The "default" keyword is used as the last case label to handle the scenario where none of the case labels match the expression. If no match is found, the code within the "default" block is executed. In the example, if the value of "day" is not between 1 and 7, the "default" block will execute, and the value of "dayName" will be "Invalid day".