Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A Java switch expression is a control flow construct that evaluates a target variable and routes execution through matching branches to compute and return a single value. Standardized in Java 14, it evolves the traditional switch statement from a purely procedural branching mechanism into an expression that evaluates to a result.

Core Mechanics

  • Value Resolution and Typing: The compiler determines the final type of the switch expression based on the types of all branch results. If the branches return mixed primitive types (e.g., an int and a double), the compiler applies numeric promotion rules (resulting in a double). For reference types, the compiler determines the least upper bound (the most specific common supertype) of all branch types.
  • Exhaustiveness: The compiler strictly enforces that a switch expression covers all possible values of the target variable. If the target type is an enum or a sealed class, explicitly listing all permitted values satisfies this requirement. For all other types (e.g., int, String), a default branch is mandatory.
  • Null Handling: Evaluating a switch expression with a null target variable throws a NullPointerException by default. As of Java 21, this behavior can be intercepted by explicitly declaring a case null branch.
  • Control Flow Restrictions: Jump statements such as return, continue, and unlabelled break cannot be used to transfer control outside of a switch expression. Attempting to return from the enclosing method from within a switch expression block results in a compile-time error.
  • No Fall-Through (Arrow Syntax): Using the -> operator binds a case label directly to an expression, a block, or a throw statement. Execution evaluates only the matched branch and terminates, eliminating the need for break statements and preventing accidental fall-through.
  • Multiple Case Labels: Multiple matching constants can be grouped in a single case declaration using a comma-separated list.

Syntax and Structure

Standard Arrow Syntax When a branch requires only a single expression, the value of that expression is automatically yielded as the result of the switch expression.
public class SwitchArrowExample {
    public static void main(String[] args) {
        int dayOfWeek = 3;
        
        String dayType = switch (dayOfWeek) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid day";
        };
        
        System.out.println(dayType);
    }
}
Block Syntax with yield If a branch requires multiple statements (e.g., local variable declarations or complex logic), the right side of the -> operator must be enclosed in a block {}. The yield keyword is required to return the value from that specific block. yield transfers the value to the switch expression itself so it can complete its evaluation; it does not act like a return statement that exits the enclosing method.
public class SwitchBlockExample {
    public static void main(String[] args) {
        String status = "PENDING";
        
        int statusCode = switch (status) {
            case "APPROVED" -> 200;
            case "PENDING" -> {
                System.out.println("Status is pending approval.");
                yield 202; 
            }
            case null -> 404; // Java 21+ null handling
            default -> {
                System.out.println("Unknown status.");
                yield 400;
            }
        };
        
        System.out.println(statusCode);
    }
}
Traditional Colon Syntax (with yield) Switch expressions can also utilize the traditional colon (:) syntax. Because it is an expression rather than a statement, break cannot be used to return a value. Instead, yield must be explicitly declared for every branch to return the evaluated result. Fall-through still occurs in this syntax unless interrupted by yield or throw.
public class SwitchColonExample {
    public enum TrafficLight { RED, YELLOW, GREEN }

    public static void main(String[] args) {
        TrafficLight light = TrafficLight.RED;
        
        // Exhaustive enum evaluation requires no default branch
        String action = switch (light) {
            case RED:
            case YELLOW:
                yield "Stop";
            case GREEN:
                yield "Go";
        };
        
        System.out.println(action);
    }
}
Master Java with Deep Grasping Methodology!Learn More