Control Flow: Switch Expressions & Pattern Matching (Java 21)
1Concept
Java 21 supports Pattern Matching for switch and Switch Expressions with arrow syntax (->), yielding values directly without break statements, and exhaustive type matching on Sealed Classes and Records.
2Architecture Diagram
String status = switch (statusCode) {
case 200, 201 -> "OK / Created";
case 400, 404 -> "Client Error";
case 500 -> "Server Fault";
default -> "Unknown";
};3Code Example
Stage 0 Language Foundations
public class SwitchPatternDemo {
sealed interface ApiResponse permits SuccessResponse, ErrorResponse {}
record SuccessResponse(String data, int code) implements ApiResponse {}
record ErrorResponse(String errorMessage, int code) implements ApiResponse {}
public static String handleResponse(ApiResponse response) {
// Java 21 Pattern Matching for switch
return switch (response) {
case SuccessResponse s when s.code() == 200 -> "Success: " + s.data();
case SuccessResponse s -> "Success (Status " + s.code() + "): " + s.data();
case ErrorResponse e when e.code() >= 500 -> "Critical Server Failure: " + e.errorMessage();
case ErrorResponse e -> "Client Error (" + e.code() + "): " + e.errorMessage();
};
}
public static void main(String[] args) {
ApiResponse r1 = new SuccessResponse("Payload loaded", 200);
ApiResponse r2 = new ErrorResponse("Internal DB Timeout", 503);
System.out.println(handleResponse(r1));
System.out.println(handleResponse(r2));
}
}4Expected Output
Success: Payload loaded Critical Server Failure: Internal DB Timeout
5Key Takeaways
- ✓Switch expressions with -> return values and eliminate forgotten break statement bugs.
- ✓Guarded patterns (when clause) allow fine-grained boolean conditions inside switch cases.
- ✓Switching over sealed hierarchies guarantees compile-time exhaustiveness checks.