SoFunction
Updated on 2025-04-25

Usage of Java switch case statements and common problems

switchThe statement is a multi-branch selection structure in Java, used to replace multipleif...else ifScenario. 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 bebyteshortintcharStringor 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 outswitchSentence. If omittedbreak, the program will continue to execute the next onecase(calledswitch penetration)。
  • default: Optional, handles all mismatch cases, similarelse

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,switchsupportStringtype.

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

switchCan andenumTypes 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

MultiplecaseBranches 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 encountersbreakorswitchFinish.

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

  • numberEqual to2, matchcase 2, execute its code.
  • Because there is nobreak, continue to executecase 3anddefault

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,switchCan 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 needbreak
  • Reduce redundant code.

4.2 Multi-line code block (Java 13+)

In Java 13,switchExpressions 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

  • switchForgot to add it to the branchbreakIt will lead to penetration.
  • If there is no need to penetrate, be sure to be in eachcaseAdd after branchbreak

5.2 The location of default

  • defaultCan appear inswitchanywhere, but usually written at the end, enhancing readability.

5.3 Limitations of expression types

  • switchThe type of an expression must be one of the following:
    • byteshortintchar(and their packaging class)
    • String
    • Enumeration type (enum

5.4 Handling NullPointerException

ifswitchThe expression isnullAnd 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 useswitchBefore, 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 byteshortintcharString, enum type (enum)wait.
break and default breakUsed to prevent penetration,defaultUsed 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+) useyieldReturn 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 useswitchStatements 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 detailswitchBasic knowledge, advanced usage and optimization techniques of case statements. In the next section, we will further discussswitchAdvanced features, performance optimization, and solutions to common problemsas well asApplication scenarios in practice, help you to have a more comprehensive graspswitchStatements are used efficiently in actual development.

7. Advanced features of switch

7.1 switch and multi-value matching

Starting with Java 12,switchExpressions support multi-value matching, which greatly simplifies multiplecaselogic 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 multiplecaseValue, reduce code redundancy.
  • More clearly express the intention of multiple values ​​corresponding to the same logic.

7.2 Use of yield

In Java 13,switchExpressions have been introducedyieldKeywords 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

  • yieldReplacedreturn, used forswitchReturn value in the expression.
  • Supports multi-line code logic, enhancing readability and flexibility.

7.3 Nesting of switch

In some complex scenarios, nestedswitchStatements 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

switchCommonly 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,switchandif...elseThe performance difference is not large.
    • For a large number of conditions,switchUsually more thanif...elseMore efficient, because the compiler will optimizeswitchIt is a jump table or binary search.
  • readability
    • switchMore suitable for handling branch selections that are fixed values.
    • if...elseMore 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 addedbreakIt will lead to unexpected penetration, and the subsequent executioncaseCode.
  • Solution: Make sure everycaseBranches withbreakorreturnEnd, or useswitchExpression (Java 12+), which will not penetrate by default.

8.3 Use of default

  • suggestion: Always providedefaultBranch, 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

  • switchDirect matching is not supportednullValue, if passed innull, will be thrownNullPointerException
  • Solution: In useswitchCheck 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

switchVery 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

switchIt 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 useswitchExpressions (Java 12+)

10.2 Best Practices

  • Choose the right structure: For fixed-value branches, priority is usedswitch, especially enum and string matching.
  • Avoid penetration: Make sure everycaseusebreakorreturnFinish.
  • Always providedefault: Handle unexpected situations and enhance the robustness of the code.
  • useswitchExpressions: In Java 12+, it is recommended to useswitchExpressions simplify code logic.
  • Process in advancenullValue: AvoidnullCauseNullPointerException

Through reasonable useswitchThe 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!