Home  >  Article  >  Java  >  Usage of switch case statement in java

Usage of switch case statement in java

下次还敢
下次还敢Original
2024-05-01 17:45:46913browse

Usage of switch-case statement in Java

In Java, the switch-case statement is a multi-way selection statement used to Values ​​execute different blocks of code. It is similar to the switch statement in languages ​​such as C and C.

Syntax:

<code class="java">switch (variable) {
    case value1:
        // 代码块 1
        break;
    case value2:
        // 代码块 2
        break;
    ...
    default:
        // 默认代码块
}</code>

Usage:

  1. Variable type: variable can be byte, short, int, char, String, or an enumeration type.
  2. Value comparison: The value following case must match the value of variable.
  3. Code block: The code block to be executed is specified after each case.
  4. break statement: The break statement is used to exit the switch statement immediately after executing a block of code. If there is no break statement, execution will continue with subsequent case blocks.
  5. default block: The default block is optional and is used to execute code when no other case matches.

Example:

<code class="java">int dayOfWeek = 3;

switch (dayOfWeek) {
    case 1:
        System.out.println("星期一");
        break;
    case 2:
        System.out.println("星期二");
        break;
    case 3:
        System.out.println("星期三");
        break;
    default:
        System.out.println("未知的星期");
}</code>

Advantages:

  • The code is highly readable and easy to maintain.
  • Performance is better than if-else statements because the compiler can optimize switch-case statements.

Note:

  • Each case value must be a constant, not a variable.
  • case Value cannot be repeated.

The above is the detailed content of Usage of switch case statement in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn