Java•Switch Statement
Java Switch Statement and Modern Switch Expressions (Java 14+)
Modern Java switch expressions use arrow syntax (->) which eliminates break and allows returning values.
Syntax
String res = switch (code) {
case 200 -> "OK";
default -> "Unknown";
};
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| case val -> | Arrow Case | Executes without fallthrough; can yield a return value. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Java locally:
public class Main {
public static void main(String[] args) {
String httpMethod = "POST";
// Modern Java 14+ Switch Expression with Arrow Syntax
String action = switch (httpMethod) {
case "GET" -> "Read resource";
case "POST", "PUT" -> "Mutate / create resource";
case "DELETE" -> "Purge record";
default -> "Unsupported verb: " + httpMethod;
};
System.out.println("Method: " + httpMethod);
System.out.println("Action: " + action);
}
}Expected Output:
Method: POST Action: Mutate / create resource
How It Works: Step-by-Step
- Lines 6-11: Switch expression returns string value directly into action variable.
- Line 8: Combines multiple cases with comma separation.
Key Concepts
- Modern switch expressions (Java 14+) do not require break statements.
- Arrow cases (->) prevent accidental fallthrough bugs.
- Switch can be used on int, char, byte, short, String, and enums.
Common Mistake: Missing default case in a switch expression that produces a value
Switch expressions must be exhaustive; they must cover every possible case or define default.
❌ Incorrect
int res = switch (val) { case 1 -> 10; }; // Compile Error: does not cover all possible input values✅ Correct
int res = switch (val) { case 1 -> 10; default -> 0; };Related Java Tutorials & Compiler
Java If...Else and Ternary Conditional Statements
Implement decision-making logic using if, else if, else, and ternary operators.
Java For Loops and Enhanced For-Each Loop with Examples
Master traditional counting for loops and enhanced for-each iteration over arrays and collections.
Java Methods: Static Methods, Return Values, and Overloading
Learn how to declare methods, pass arguments, return values, and overload method signatures.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.