switch
The statement is a multi-branch selection structure in Java, used to replace multipleif...else if
Scenario. It executes matching code blocks in the branch based on the value of a variable.
1. Basic syntax
switch (expression) { case value1: // Code executed when the value of the expression is equal to the value 1 break; // Optional, jump out of the switch statement case value2: // Code executed when the value of the expression is equal to the value 2 break; ... default: // Code executed when all cases do not match break; // Optional}
-
expression: Can be
byte
、short
、int
、char
、String
or enumeration type (enum
)。 - case: The value of each branch must be a constant, and the value type must be consistent with the type of the expression.
-
break: Used to jump out
switch
Sentence. If omittedbreak
, the program will continue to execute the next onecase
(calledswitch penetration)。 -
default: Optional, handles all mismatch cases, similar
else
。
2. Sample code
2.1 Simple switch example
public class Main { public static void main(String[] args) { int day = 3; switch (day) { case 1: ("Monday"); break; case 2: ("Tuesday"); break; case 3: ("Wednesday"); break; case 4: ("Thursday"); break; case 5: ("Friday"); break; default: ("Weekend"); } } }
Output:
Wednesday
2.2 Use a switch of String type
Starting with Java 7,switch
supportString
type.
public class Main { public static void main(String[] args) { String color = "Red"; switch (color) { case "Red": ("Stop!"); break; case "Yellow": ("Caution!"); break; case "Green": ("Go!"); break; default: ("Invalid color."); } } }
Output:
Stop!
2.3 Use enum type switch
switch
Can andenum
Types are used in conjunction, which is very useful when dealing with values of fixed sets.
public class Main { public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { Day today = ; switch (today) { case MONDAY: ("Start of the week."); break; case FRIDAY: ("End of the work week."); break; case SATURDAY: case SUNDAY: ("It's the weekend!"); break; default: ("Midweek day."); } } }
Output:
End of the work week.
2.4 Multiple cases merge
Multiplecase
Branches can be merged and processed to avoid duplicate code.
public class Main { public static void main(String[] args) { int month = 7; switch (month) { case 12: case 1: case 2: ("Winter"); break; case 3: case 4: case 5: ("Spring"); break; case 6: case 7: case 8: ("Summer"); break; case 9: case 10: case 11: ("Autumn"); break; default: ("Invalid month"); } } }
Output:
Summer
3. switch penetration phenomenon
If there is no in the branchbreak
, the program will continue to execute subsequent branch code until it encountersbreak
orswitch
Finish.
Example: Demonstration penetration
public class Main { public static void main(String[] args) { int number = 2; switch (number) { case 1: ("One"); case 2: ("Two"); case 3: ("Three"); default: ("Default"); } } }
Output:
Two
Three
Default
analyze:
-
number
Equal to2
, matchcase 2
, execute its code. - Because there is no
break
, continue to executecase 3
anddefault
。
Correct writing: Join break
public class Main { public static void main(String[] args) { int number = 2; switch (number) { case 1: ("One"); break; case 2: ("Two"); break; case 3: ("Three"); break; default: ("Default"); } } }
Output:
Two
4. Advanced usage of switch
4.1 switch expression (Java 12+)
Starting with Java 12,switch
Can be used as an expression and return a value.
grammar
int result = switch (expression) { case value1 -> value1Results; case value2 -> value2Results; default -> Default result; };
Example: Return value
public class Main { public static void main(String[] args) { int day = 5; String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; case 4 -> "Thursday"; case 5 -> "Friday"; case 6, 7 -> "Weekend"; default -> "Invalid day"; }; (result); } }
Output:
Friday
benefit:
- Simplified syntax, no need
break
。 - Reduce redundant code.
4.2 Multi-line code block (Java 13+)
In Java 13,switch
Expressions support multi-line code blocks.
Example: Multi-line code block
public class Main { public static void main(String[] args) { int day = 5; String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 5 -> { ("More logic for Friday..."); yield "Friday"; // Use yield to return value } default -> "Invalid day"; }; (result); } }
Output:
More logic for Friday...
Friday
5. Frequently Asked Questions and Precautions
5.1 Forgot break
-
switch
Forgot to add it to the branchbreak
It will lead to penetration. - If there is no need to penetrate, be sure to be in each
case
Add after branchbreak
。
5.2 The location of default
-
default
Can appear inswitch
anywhere, but usually written at the end, enhancing readability.
5.3 Limitations of expression types
-
switch
The type of an expression must be one of the following:-
byte
,short
,int
,char
(and their packaging class) String
- Enumeration type (
enum
)
-
5.4 Handling NullPointerException
ifswitch
The expression isnull
And the type isString
, will be thrownNullPointerException
。
Error Example
public class Main { public static void main(String[] args) { String color = null; switch (color) { // NullPointerException will be thrown case "Red": ("Stop"); break; default: ("Invalid color"); } } }
Solution
In useswitch
Before, check whether it isnull
。
if (color == null) { ("Invalid color"); } else { switch (color) { case "Red": ("Stop"); break; default: ("Invalid color"); } }
6. Summary
characteristic | describe |
---|---|
Data types supported by switch |
byte , short , int , char , String , enum type (enum )wait. |
break and default |
break Used to prevent penetration,default Used to handle all mismatch cases. |
switch expression (Java 12+) | Simplified syntax, directly return value withoutbreak , clearer and more concise. |
Multi-line code block (Java 13+) | useyield Return value, supports multi-line logical processing. |
Applicable scenarios | Multi-value matching and equal value judgment (such as menu options, enumeration status, string matching, etc.). |
Through reasonable useswitch
Statements can make the code logic clearer and more efficient, especially when dealing with multi-branch selection, which is a very intuitive solution!
We have already discussed in Java in detailswitch
Basic knowledge, advanced usage and optimization techniques of case statements. In the next section, we will further discussswitch
Advanced features, performance optimization, and solutions to common problemsas well asApplication scenarios in practice, help you to have a more comprehensive graspswitch
Statements are used efficiently in actual development.
7. Advanced features of switch
7.1 switch and multi-value matching
Starting with Java 12,switch
Expressions support multi-value matching, which greatly simplifies multiplecase
logic between.
Example: Multiple cases match the same logic
public class Main { public static void main(String[] args) { int day = 6; String result = switch (day) { case 1, 2, 3, 4, 5 -> "Weekday"; case 6, 7 -> "Weekend"; default -> "Invalid day"; }; (result); } }
Output:
Weekend
benefit:
- Use commas to separate multiple
case
Value, reduce code redundancy. - More clearly express the intention of multiple values corresponding to the same logic.
7.2 Use of yield
In Java 13,switch
Expressions have been introducedyield
Keywords are used to return the calculation results. It can support logical processing of multiple lines and return a value.
Multi-line logic yield example
public class Main { public static void main(String[] args) { int number = 2; String result = switch (number) { case 1 -> "One"; case 2 -> { ("Processing case 2..."); yield "Two"; // Return value } case 3 -> "Three"; default -> "Unknown"; }; ("Result: " + result); } }
Output:
Processing case 2...
Result: Two
analyze:
-
yield
Replacedreturn
, used forswitch
Return value in the expression. - Supports multi-line code logic, enhancing readability and flexibility.
7.3 Nesting of switch
In some complex scenarios, nestedswitch
Statements to handle multi-layer logic.
Example: Nested switch to achieve multi-condition judgment
public class Main { public static void main(String[] args) { String role = "Manager"; String department = "HR"; switch (role) { case "Manager": switch (department) { case "HR": ("HR Manager"); break; case "IT": ("IT Manager"); break; default: ("General Manager"); } break; case "Employee": ("Employee"); break; default: ("Unknown role"); } } }
Output:
HR Manager
7.4 Using switch to handle complex logic
switch
Commonly used to deal with predefined conditions, menu options, status processing and other scenarios. Combining methods and enumerations can further improve readability and flexibility.
Example: Combining enumeration and method processing state
public class Main { public enum OrderStatus { PENDING, PROCESSING, COMPLETED, CANCELED } public static void main(String[] args) { OrderStatus status = ; String message = processOrderStatus(status); (message); } public static String processOrderStatus(OrderStatus status) { return switch (status) { case PENDING -> "Your order is pending."; case PROCESSING -> "Your order is being processed."; case COMPLETED -> "Your order has been completed."; case CANCELED -> "Your order has been canceled."; }; } }
Output:
Your order is being processed.
8. Performance optimization and precautions
8.1 Performance comparison between switch and if...else
-
performance:
- For a small number of conditions,
switch
andif...else
The performance difference is not large. - For a large number of conditions,
switch
Usually more thanif...else
More efficient, because the compiler will optimizeswitch
It is a jump table or binary search.
- For a small number of conditions,
-
readability:
-
switch
More suitable for handling branch selections that are fixed values. -
if...else
More suitable for handling complex Boolean expressions or interval judgments.
-
Example: Interval judgment is more suitable for use if...else
public class Main { public static void main(String[] args) { int score = 85; if (score >= 90) { ("Grade: A"); } else if (score >= 80) { ("Grade: B"); } else if (score >= 70) { ("Grade: C"); } else { ("Grade: F"); } } }
8.2 Avoid penetration (unintentional fall-through)
- Not added
break
It will lead to unexpected penetration, and the subsequent executioncase
Code. -
Solution: Make sure every
case
Branches withbreak
orreturn
End, or useswitch
Expression (Java 12+), which will not penetrate by default.
8.3 Use of default
-
suggestion: Always provide
default
Branch, even if you think all possible values are covered. - effect: Handle unexpected values to avoid logical vulnerabilities in the program.
8.4 Avoid null value causing problems
-
switch
Direct matching is not supportednull
Value, if passed innull
, will be thrownNullPointerException
。 -
Solution: In use
switch
Check whether it isnull
。
9. Application scenarios in actual development
9.1 Menu System
Example: Simple menu system
import ; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(); ("Menu:"); ("1. Start Game"); ("2. Load Game"); ("3. Exit"); ("Enter your choice: "); int choice = (); switch (choice) { case 1 -> ("Game Started!"); case 2 -> ("Game Loaded!"); case 3 -> ("Exiting..."); default -> ("Invalid choice!"); } } }
9.2 State Machine
switch
Very suitable for implementing state machines, used to perform different operations according to the current state.
Example: Simple State Machine
public class Main { public enum Light { RED, YELLOW, GREEN } public static void main(String[] args) { Light current = ; switch (current) { case RED -> ("Stop!"); case YELLOW -> ("Ready!"); case GREEN -> ("Go!"); } } }
9.3 Error code handling
switch
It can be used to return the corresponding error message according to the error code.
Example: According to the error code prompt information
public class Main { public static void main(String[] args) { int errorCode = 404; String message = switch (errorCode) { case 200 -> "OK"; case 400 -> "Bad Request"; case 404 -> "Not Found"; case 500 -> "Internal Server Error"; default -> "Unknown Error"; }; ("Error: " + message); } }
10. Summary and Suggestions
10.1 Applicable scenarios
Scene | Recommended Structure |
---|---|
Multi-branch selection for fixed values | useswitch
|
Interval judgment or complex boolean logic | useif...else
|
Selection structure that requires return value | useswitch Expressions (Java 12+) |
10.2 Best Practices
-
Choose the right structure: For fixed-value branches, priority is used
switch
, especially enum and string matching. -
Avoid penetration: Make sure every
case
usebreak
orreturn
Finish. -
Always provide
default
: Handle unexpected situations and enhance the robustness of the code. -
use
switch
Expressions: In Java 12+, it is recommended to useswitch
Expressions simplify code logic. -
Process in advance
null
Value: Avoidnull
CauseNullPointerException
。
Through reasonable useswitch
The case statement can not only improve the readability and efficiency of the code, but also better cope with complex scenarios of multi-conditional branches!
Summarize
This is the article about the usage and common questions of Java switch case statements. For more related contents of Java switch case statements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!