Preface
In Java programming,switch
A statement is a control flow statement that is used to execute different code blocks according to the value of a variable. andif-else
Compared with statements,switch
Statements are more concise and efficient in some cases. When multiple conditions need to be processed,switch
Statements can also be optimized through certain methods. This article will introduce in Java in detailswitch case
How to use it includes how to deal with multiple conditions.
Basic syntax
switch
The basic syntax of a statement is as follows:
switch (expression) { case value1: // Code block break; case value2: // Code block break; // More cases default: // Default code block}
-
expression
: Expressions used for judgment, usually integers, strings, enums, etc. -
case value
: The branch that matches the expression value. -
break
: Used to terminateswitch
Statement to prevent subsequent cases from being executed. -
default
: A block of code executed when all cases do not match.
Handle multiple conditions
existswitch
In a statement, if different case branches need to execute the same code, they can be merged. This method can effectively reduce code redundancy and improve readability.
Example 1: Merge multiple cases of the same code
char grade = 'B'; switch (grade) { case 'A': case 'B': case 'C': ("pass"); break; case 'D': case 'E': ("Not passed"); break; default: ("Invalid results"); }
In this example,A
、B
、C
Three case branches execute the same code, and by combining them together, the code can be simplified.
Example 2: Merge multiple cases via string
Java 7 has started to support the use of strings asswitch
expression.
String role = "admin"; switch (role) { case "admin": case "administrator": ("Access Management Function"); break; case "user": case "guest": ("Access User Features"); break; default: ("Invalid Role"); }
In this example,admin
andadministrator
Both case branches execute the same code.
Advanced usage
Use enumeration types
Using enum types can make the code clearer and more readable, and avoid spelling errors caused by string constants.
Define enum types
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Using enumeration typeswitch
Statement
Day today = ; switch (today) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: ("Working Day"); break; case SATURDAY: case SUNDAY: ("weekend"); break; }
Use constants
If there are multiple constants to be judged, you can also useswitch
Statements are optimized.
Define constants
public class Constants { public static final int RED = 1; public static final int GREEN = 2; public static final int BLUE = 3; public static final int YELLOW = 4; }
Switch statement using constants
int color = ; switch (color) { case : case : ("Warm tones"); break; case : case : ("Cool tones"); break; default: ("Unknown Color"); }
Nested switch statements
In some complex scenarios, nesting may be requiredswitch
Statement.
String userType = "admin"; String action = "delete"; switch (userType) { case "admin": switch (action) { case "create": ("Administrator creates content"); break; case "delete": ("Administrator deletes content"); break; default: ("Invalid operation"); } break; case "user": switch (action) { case "create": ("User-created content"); break; case "delete": ("User has no right to delete content"); break; default: ("Invalid operation"); } break; default: ("Unknown user type"); }
Optimization through function
In some cases, further optimization can be achieved by extracting duplicate code into a function.switch
Statement.
public class SwitchCaseExample { public static void main(String[] args) { char grade = 'B'; printGradeMessage(grade); } public static void printGradeMessage(char grade) { switch (grade) { case 'A': case 'B': case 'C': printPassMessage(); break; case 'D': case 'E': printFailMessage(); break; default: printInvalidMessage(); } } private static void printPassMessage() { ("pass"); } private static void printFailMessage() { ("Not passed"); } private static void printInvalidMessage() { ("Invalid results"); } }
Summarize
This is the article about the multiple conditional processing methods of Switch Case in Java. For more information about Java Switch Case, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!