Java:Java Switch Statement and Modern Switch Expressions (Java 14+)
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:

ParameterTypeDescription
case val ->Arrow CaseExecutes without fallthrough; can yield a return value.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler