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:
variable
can be byte
, short
, int
, char
, String
, or an enumeration type. case
must match the value of variable
. case
. 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. 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:
if-else
statements because the compiler can optimize switch-case
statements. Note:
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!