Java Switch Statement: Traditional Switch to Modern Pattern Matching

The switch statement provides an efficient multi-way branching mechanism, testing an expression against multiple matching constant values (cases). In modern Java (Java 14 through Java 21 LTS), switch has evolved from a basic statement into a powerful Switch Expression supporting arrow syntax, yield, and Pattern Matching.

1. Traditional Switch Statement (Pre-Java 14)

Traditional switch relies on colon labels and mandatory break statements to prevent case fallthrough:

int dayOfWeek = 3;
String dayName;

switch (dayOfWeek) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
    case 7:
        dayName = "Weekend";
        break;
    default:
        dayName = "Invalid Day Number";
        break;
}
System.out.println("Day: " + dayName); // Wednesday

2. Modern Switch Expressions with Arrow Syntax (Java 14+)

Modern switch can be used directly as an expression that returns a value. It uses clean arrow syntax (->) with zero risk of accidental fallthrough and supports comma-separated case labels:

int day = 6;
// Switch expression directly assigns return value to variable:
String typeOfDay = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7          -> "Weekend";
    default            -> "Invalid Day";
};
System.out.println("Status: " + typeOfDay); // Weekend

3. Multi-Line Blocks & the yield Keyword

When an arrow case requires multiple statements or calculations, enclose the block in curly braces and return the final value using yield:

String role = "ADMIN";
int accessLevel = switch (role) {
    case "ADMIN" -> {
        System.out.println("Logging administrative access...");
        yield 100; // Returns 100
    }
    case "EDITOR", "AUTHOR" -> 50;
    case "VIEWER" -> 10;
    default -> 0;
};

4. Modern Java 21 Pattern Matching for Switch

Finalized in Java 21 LTS, pattern matching allows switching directly on arbitrary object types, casting types automatically, and even matching null:

public class PatternMatchingSwitchDemo {
    public static void inspectObject(Object obj) {
        // Direct pattern matching in switch (Java 21 LTS)
        String description = switch (obj) {
            case null               -> "Object is NULL!";
            case Integer i          -> "Integer value: " + i + ", Square: " + (i * i);
            case String s           -> "String of length " + s.length() + ": " + s.toUpperCase();
            case Double d           -> "Floating point double: " + d;
            case int[] arr          -> "Array of size: " + arr.length;
            default                 -> "Unknown object type: " + obj.toString();
        };

        System.out.println(description);
    }

    public static void main(String[] args) {
        inspectObject(42);               // Matches Integer
        inspectObject("Veewom Java");     // Matches String
        inspectObject(null);             // Safely matches null!
    }
}

University Exam Corner (BCA / B.Sc CS)

Exam Question: "Can a switch statement in Java evaluate String values? Since which version?"

Answer: Yes! Switching on String objects was introduced in Java 7. Under the hood, the compiler converts string comparisons into hashCode() integer lookups paired with equals() verification to avoid hash collisions.

Next Step

Now let us explore iterative execution starting with the entry-controlled While loop. Proceed to: Java While Loop →

Frequently Asked Questions (FAQ)

Q1. What data types are supported in a Java switch expression?
Traditional switch supports byte, short, char, int, their corresponding Wrapper classes, String (Java 7+), and Enums (Java 5+). Modern Java 21 Pattern Matching expands switch to accept ANY Object type, Records, and Interfaces.
Q2. What is 'case fallthrough' in a traditional switch statement?
In traditional switch statements, if a case block does not terminate with a 'break' statement, execution falls through into subsequent case blocks regardless of whether their case labels match. Modern arrow syntax (->) eliminates accidental fallthrough.
Q3. How does the 'yield' keyword work in Java switch expressions?
Introduced in Java 14, 'yield' is used inside multi-line switch expression blocks to return a value from the switch block back to the caller variable.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Java If-Else Conditions →

Comparing switch with if-else.

Break & Continue →

Exiting switch cases.

Java Records →

Deconstructing records in switch.

Java Syntax Rules →

Language conventions.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!