Appearance
Switch Statement
In addition to the if
statement, there is also a conditional judgment, which is to execute different branches based on the result of a certain expression.
For example, in a game, let the user choose an option:
- Single player mode
- Multiplayer mode
- Exit game
At this time, the switch
statement comes in handy.
switch
statement jumps to the matching case
result based on the result calculated by switch (expression)
, and then continues to execute subsequent statements until it encounters break
to end execution.
Let's look at an example:
java
public class Main {
public static void main(String[] args) {
int option = 1;
switch (option) {
case 1:
System.out.println("Selected 1");
break;
case 2:
System.out.println("Selected 2");
break;
case 3:
System.out.println("Selected 3");
break;
}
}
}
Modify option values to 1
, 2
, and 3
respectively, and observe the execution results.
If the value of option
does not match any case
, such as option = 99
, then the switch
statement will not execute any statement. At this time, you can add a default
to switch
statement. When no case
is matched, default
is executed:
java
public class Main {
public static void main(String[] args) {
int option = 99;
switch (option) {
case 1:
System.out.println("Selected 1");
break;
case 2:
System.out.println("Selected 2");
break;
case 3:
System.out.println("Selected 3");
break;
default:
System.out.println("Selected other");
break;
}
}
}
If the switch
statement is translated into an if
statement, then the above code is equivalent to:
java
if (option == 1) {
System.out.println("Selected 1");
} else if (option == 2) {
System.out.println("Selected 2");
} else if (option == 3) {
System.out.println("Selected 3");
} else {
System.out.println("Selected other");
}
Compared with if ... else
if statement, for the case of multiple ==
judgments, it is clearer to use switch
structure.
At the same time, note that the above "translation" can only be matched if the break
statement is correctly written for each case
in the switch
statement.
When using switch
, please note that case
statement does not have curly braces {}
. Moreover, case
statement is " penetrating ", and omitting break
will lead to unexpected results:
java
public class Main {
public static void main(String[] args) {
int option = 2;
switch (option) {
case 1:
System.out.println("Selected 1");
case 2:
System.out.println("Selected 2");
case 3:
System.out.println("Selected 3");
default:
System.out.println("Selected other");
}
}
}
When option = 2
, "Selected 2"
, "Selected 3"
, and "Selected other"
will be output in sequence. The reason is that starting from matching case 2
, all subsequent statements will be executed until the break
statement is encountered. Therefore, never forget to write break
at any time.
If there are several case
statements executing the same set of statement blocks, you can write it like this:
java
public class Main {
public static void main(String[] args) {
int option = 2;
switch (option) {
case 1:
System.out.println("Selected 1");
break;
case 2:
case 3:
System.out.println("Selected 2, 3");
break;
default:
System.out.println("Selected other");
break;
}
}
}
When using switch
statement, as long as there is break
, the order of case
does not affect the program logic:
java
switch (option) {
case 3:
...
break;
case 2:
...
break;
case 1:
...
break;
}
However, it is still recommended to arrange them in natural order for easier reading.
The switch
statement can also match strings. When string matching, "content equality" is compared. For example:
java
public class Main {
public static void main(String[] args) {
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("Selected apple");
break;
case "pear":
System.out.println("Selected pear");
break;
case "mango":
System.out.println("Selected mango");
break;
default:
System.out.println("No fruit selected");
break;
}
}
}
The switch
statement can also use enumeration types. We will explain enumeration types later.
Compilation Check
When using an IDE, you can automatically check whether break
statements and default
statements are missing by turning on the IDE's compilation check.
In Idea, select Preferences
- Editor
- Inspections
- Java
- Control flow issues
and mark the following inspection as Warning:
- 'switch' statement without 'default' branch
- Fallthrough in 'switch' statement
When there is a problem with the switch
statement, you can get a warning prompt in the IDE.
Switch Expression
When using switch
, if break
is omitted, serious logical errors will occur, and it is difficult to find errors in the source code.
Starting from Java 12, switch
statement is upgraded to a more concise expression syntax, using a method similar to pattern matching (Pattern Matching) to ensure that only one path will be executed and no break
statement is required:
java
public class Main {
public static void main(String[] args) {
String fruit = "apple";
switch (fruit) {
case "apple" -> System.out.println("Selected apple");
case "pear" -> System.out.println("Selected pear");
case "mango" -> {
System.out.println("Selected mango");
System.out.println("Good choice!");
}
default -> System.out.println("No fruit selected");
}
}
}
Note that the new syntax uses ->
. If there are multiple statements, they need to be enclosed in {}
. Do not write break
statements, because the new syntax will only execute matching statements and has no penetration effect.
Many times, we may also use switch
statement to assign a value to a variable. For example:
java
int opt;
switch (fruit) {
case "apple":
opt = 1;
break;
case "pear":
case "mango":
opt = 2;
break;
default:
opt = 0;
break;
}
Using the new switch
syntax, not only does break
need not be required, but the value can also be returned directly. Rewrite the above code as follows:
java
public class Main {
public static void main(String[] args) {
String fruit = "apple";
int opt = switch (fruit) {
case "apple" -> 1;
case "pear", "mango" -> 2;
default -> 0;
}; // 注意赋值语句要以;结束
System.out.println("opt = " + opt);
}
}
This results in cleaner code.
yield
Most of the time, inside switch
expression, we return simple values.
However, if complex statements are needed, we can also write many statements and put them in {...}
, and then use yield to return a value as the return value of the switch
statement:
java
public class Main {
public static void main(String[] args) {
String fruit = "orange";
int opt = switch (fruit) {
case "apple" -> 1;
case "pear", "mango" -> 2;
default -> {
int code = fruit.hashCode();
yield code; // switch statement return value
}
};
System.out.println("opt = " + opt);
}
}
Summary
The switch
statement can make multiple selections, and then execute the subsequent code of the matching case
statement;
The calculation result of switch
must be an integer, string or enumeration type;
Be careful not to miss out break
, it is recommended to turn on fall-through
warning;
Always write default
, it is recommended to turn on the missing default
warning;
Starting from Java 14, the switch
statement is officially upgraded to an expression, break
is no longer required, and yield
return value is allowed.