> ## 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.

# Java Switch Expression

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.

```java theme={"dark"}
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.

```java theme={"dark"}
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`.

```java theme={"dark"}
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);
    }
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Java Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
