Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. switch Statement / switch Expression (Java)

switch Statement / switch Expression (Java)

A conditional branching construct. The switch statement branches execution based on the value of a single variable or expression. The switch expression, formalized in Java 14, uses -> (lambda style) to return values concisely. This page covers the differences from the traditional switch statement (case, break, default), how to use switch with strings and enums, and returning values with the yield keyword.

Syntax

// Traditional switch statement (Java 1.0+)
// You must write break at the end of each case, or execution falls through to the next case
switch (variable or expression) {
    case value1:
        // Executed when value1 matches
        break; // Without break, execution continues into the next case
    case value2:
        // Executed when value2 matches
        break;
    default:
        // Executed when no case matches
        break;
}

// Switch expression (Java 14+), lambda style
// The right side of -> is executed and its value is returned. No break needed. No fall-through.
String result = switch (variable or expression) {
    case value1 -> "when value1";
    case value2 -> "when value2";
    default  -> "when none match";
};

// When using a block in a switch expression, use yield to return a value
String result2 = switch (variable or expression) {
    case value1 -> {
        // Multiple statements are allowed
        System.out.println("processing for value1");
        yield "result for value1"; // yield returns the value (not return)
    }
    default -> "default";
};

// Multiple values can be combined into one case (works in both switch statements and switch expressions)
switch (variable or expression) {
    case value1, value2, value3:
        // Executed when any of value1, value2, or value3 match
        break;
}

Comparison: switch statement vs. switch expression

Featureswitch statement (traditional)switch expression (Java 14+)
Syntax stylecase value:case value ->
Fall-throughOmitting break causes execution to fall through to the next case.No fall-through.
break requiredYes (omitting causes fall-through).Not required.
Returning a valueCannot return a value (it is a statement).Can return a value (it is an expression). Assignment to a variable is also possible.
Returning from a blockN/A.Use the yield keyword.
Omitting defaultOptional (if omitted, no case is entered when nothing matches).A compile error occurs if not all patterns are covered.

Sample Code

SwitchStatement.java
public class SwitchStatement {
    public static void main(String[] args) {

        // --- Traditional switch statement (int) ---
        // Receives a sorcerer grade (1 to special) as an integer and prints the grade label
        int grade = 2;

        System.out.println("=== switch statement (traditional) ===");
        switch (grade) {
            case 1:
                System.out.println("Grade 1: Top-tier sorcerers such as Fushiguro Megumi.");
                break;
            case 2:
                System.out.println("Grade 2: The grade assigned to Itadori Yuji at provisional enrollment."); // This line is executed
                break;
            case 3:
                System.out.println("Grade 3: The grade of an average sorcerer.");
                break;
            case 4:
                System.out.println("Grade 4: The starting grade for a sorcerer.");
                break;
            default:
                System.out.println("Special Grade or unknown grade.");
                break;
        }

        // --- Fall-through example ---
        // Omitting break causes execution to continue into the next case. This can be intentional.
        // Example: grouping grade 1 and 2 as "upper grade" with the same handling
        System.out.println("\n=== Grouping multiple cases via fall-through ===");
        int rank = 1;
        switch (rank) {
            case 1:
            case 2:
                // case 1 has no break, so execution falls through to case 2
                System.out.println("Upper-grade sorcerer. (Grade: " + rank + ")");
                break;
            case 3:
            case 4:
                System.out.println("Standard-grade sorcerer. (Grade: " + rank + ")");
                break;
            default:
                System.out.println("Special Grade or unregistered.");
                break;
        }

        // --- switch statement with String ---
        // Since Java 7, String can be used as the switch argument
        String technique = "Infinite Void";

        System.out.println("\n=== switch statement with String ===");
        switch (technique) {
            case "Infinite Void":
                System.out.println("Gojo Satoru's Domain Expansion. It floods the brain with infinite information.");
                break;
            case "Blue":
            case "Red":
                System.out.println("Gojo Satoru's Reversed Cursed Technique and Cursed Technique Lapse.");
                break;
            case "Black Flash":
                System.out.println("A strike used by Itadori Yuji that warps space with cursed energy.");
                break;
            default:
                System.out.println("Unknown technique: " + technique);
                break;
        }
    }
}
javac SwitchStatement.java
java SwitchStatement
=== switch statement (traditional) ===
Grade 2: The grade assigned to Itadori Yuji at provisional enrollment.

=== Grouping multiple cases via fall-through ===
Upper-grade sorcerer. (Grade: 1)

=== switch statement with String ===
Gojo Satoru's Domain Expansion. It floods the brain with infinite information.
SwitchExpression.java
public class SwitchExpression {
    public static void main(String[] args) {

        // --- Switch expression (Java 14+), lambda style ---
        // Using -> makes it a switch expression that returns a value. No break needed.
        int grade = 2;

        // The result of a switch expression can be assigned to a variable
        String gradeLabel = switch (grade) {
            case 1    -> "Grade 1 (Fushiguro Megumi level)";
            case 2    -> "Grade 2 (Itadori Yuji level)"; // This case is selected
            case 3    -> "Grade 3";
            case 4    -> "Grade 4";
            default   -> "Special Grade or unknown";
        };
        System.out.println("Grade label: " + gradeLabel);

        // --- Grouping multiple values into one case ---
        String technique = "Red";
        String techniqueType = switch (technique) {
            case "Blue", "Red", "Purple" -> "Gojo Satoru's techniques (Lapse, Reversal, Hollow)";
            case "Infinite Void"         -> "Gojo Satoru's Domain Expansion";
            case "Black Flash", "Divergent Fist" -> "Itadori Yuji's techniques";
            default                      -> "Other technique";
        };
        System.out.println(technique + ": " + techniqueType);

        // --- Switch expression with a block (returning a value with yield) ---
        // Use a block { } when multiple statements are needed, and return the value with yield
        int cursedEnergyLevel = 85;
        String powerRating = switch (cursedEnergyLevel / 20) { // Results in a value from 0 to 5
            case 5 -> {
                System.out.println("(Special Grade cursed energy detected)");
                yield "Special Grade (Gojo Satoru level)"; // yield returns the value
            }
            case 4 -> {
                System.out.println("(Grade 1 cursed energy detected)");
                yield "Grade 1 class"; // This is executed (85 / 20 = 4)
            }
            case 3 -> {
                System.out.println("(Semi-Grade 1 cursed energy detected)");
                yield "Semi-Grade 1 class";
            }
            default -> {
                System.out.println("(Standard cursed energy detected)");
                yield "General class";
            }
        };
        System.out.println("Cursed energy rating: " + powerRating);
    }
}
javac SwitchExpression.java
java SwitchExpression
Grade label: Grade 2 (Itadori Yuji level)
Red: Gojo Satoru's techniques (Lapse, Reversal, Hollow)
(Grade 1 cursed energy detected)
Cursed energy rating: Grade 1 class
SwitchEnum.java
public class SwitchEnum {

    // Enum representing sorcerer grades from Jujutsu Kaisen
    enum SorcererGrade {
        SPECIAL_GRADE, // Special Grade
        GRADE_1,       // Grade 1
        SEMI_GRADE_1,  // Semi-Grade 1
        GRADE_2,       // Grade 2
        GRADE_3,       // Grade 3
        GRADE_4        // Grade 4
    }

    public static void main(String[] args) {

        // --- Combining enum with a switch expression ---
        // Because all possible values are known, the compiler can verify that all cases are covered.
        // However, it is safer to include default to guard against future enum additions.
        SorcererGrade grade = SorcererGrade.GRADE_1;

        // Switch expression returns a representative character name for each grade
        String representative = switch (grade) {
            case SPECIAL_GRADE -> "Gojo Satoru, Geto Suguru";
            case GRADE_1       -> "Nanami Kento, Okkotsu Yuta"; // This case is selected
            case SEMI_GRADE_1  -> "Todo Aoi";
            case GRADE_2       -> "Itadori Yuji (provisional)";
            case GRADE_3       -> "Average sorcerer";
            case GRADE_4       -> "Apprentice sorcerer";
        };
        System.out.println(grade + " representative: " + representative);

        // --- Using enum with a traditional switch statement ---
        SorcererGrade target = SorcererGrade.SPECIAL_GRADE;
        System.out.println("\n=== Response by grade (switch statement) ===");
        switch (target) {
            case SPECIAL_GRADE:
                System.out.println("Special Grade: Immediate retreat or request backup from Gojo Satoru.");
                break;
            case GRADE_1:
            case SEMI_GRADE_1:
                System.out.println("Grade 1 / Semi-Grade 1: Respond with multiple sorcerers.");
                break;
            default:
                System.out.println("Grade 2 or below: Can be handled as a standard mission.");
                break;
        }
    }
}
javac SwitchEnum.java
java SwitchEnum
GRADE_1 representative: Nanami Kento, Okkotsu Yuta

=== Response by grade (switch statement) ===
Special Grade: Immediate retreat or request backup from Gojo Satoru.

Notes

Since Java 7, the switch statement accepts String as the branch condition. However, passing null throws a NullPointerException, so always perform a null check before passing a value to switch. Supported types include int, char, byte, short, String, and enum. The types long, float, double, and boolean are not supported.

The switch expression formalized in Java 14 uses the -> style, which prevents fall-through and eliminates bugs caused by forgetting to write break. Because a switch expression is an expression rather than a statement, it can be assigned to a variable or used as a return value. When multiple statements are needed inside a block, use yield instead of return to return the value.

Combining enum with a switch expression makes the branching patterns explicit at the type level, allowing the compiler to detect unhandled cases. For details on enumerated types, see enum (Enumerated Types). For complex conditional branching, if / else if is also effective. See if / else for details.

If you find any errors or copyright issues, please .