SoFunction
Updated on 2025-04-23

Examples of multiple conditional processing methods for Switch Case in Java

Preface

In Java programming,switchA statement is a control flow statement that is used to execute different code blocks according to the value of a variable. andif-elseCompared with statements,switchStatements are more concise and efficient in some cases. When multiple conditions need to be processed,switchStatements can also be optimized through certain methods. This article will introduce in Java in detailswitch caseHow to use it includes how to deal with multiple conditions.

Basic syntax

switchThe 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 terminateswitchStatement to prevent subsequent cases from being executed.
  • default: A block of code executed when all cases do not match.

Handle multiple conditions

existswitchIn 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,ABCThree 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 asswitchexpression.

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,adminandadministratorBoth 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 typeswitchStatement

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 useswitchStatements 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 requiredswitchStatement.

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.switchStatement.

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!