What is the usage of the switch statement in Java?

In Java, the switch statement is used to choose which code block to execute based on the value of an expression. It can be used as an alternative to using multiple if-else statements for conditional logic.

The structure of a switch statement is as follows:

switch (expression) {
    case value1:
        // 执行代码块1
        break;
    case value2:
        // 执行代码块2
        break;
    case value3:
        // 执行代码块3
        break;
    ...
    default:
        // 默认执行的代码块
        break;
}

Can you explain this structure to me?

  1. An expression is a computable statement, typically a variable or constant, that produces a result.
  2. After the case keyword is followed by a constant expression representing a value. If the value of the expression is equal to the value of the case, the corresponding code block will be executed.
  3. The use of “break” in a switch statement is to exit the switch statement after executing the corresponding code block. If “break” is omitted, the execution will continue to the next case’s code block until reaching a “break” or the end of the switch statement.
  4. The default option is optional, and is used for executing a code block when the value of the expression does not match any of the cases.

Here is an example of using a switch statement:

int day = 2;
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(dayName); // 输出 "Tuesday"

In the example above, based on the value of day, the corresponding case will be chosen to execute the code block and assign the result to dayName. Finally, the value of dayName will be output as “Tuesday”. If the value of day is anything else, the default code block will be executed and the value of dayName will be set to “Invalid day”.

bannerAds