---
spec: JLS
title: "The Java Language Specification"
edition: "Java SE 17 Edition"
java_version: 17
chapter: "Chapter 14. Blocks, Statements, and Patterns"
section: "14.11"
heading: "14.11. The switch Statement"
parent: "Chapter 14. Blocks, Statements, and Patterns"
source: https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.11
id: "14.11"
url: https://jvm.obfuscated.software/jls/se17/14.11.html
raw: https://jvm.obfuscated.software/jls/se17/14.11.md
---

# 14.11. The `switch` Statement

The `switch` statement transfers control to one of several statements or expressions, depending on the value of an expression.

```
SwitchStatement:
  switch ( Expression ) SwitchBlock
```

The *Expression* is called the *selector expression*. The type of the selector expression must be `char`, `byte`, `short`, `int`, `Character`, `Byte`, `Short`, `Integer`, `String`, or an enum type ([§8.9](8.9.md)), or a compile-time error occurs.

## 14.11.1. Switch Blocks

The body of both a `switch` statement and a `switch` expression ([§15.28](15.28.md)) is called a *switch block*. This subsection presents general rules which apply to all switch blocks, whether they appear in `switch` statements or `switch` expressions. Other subsections present additional rules which apply either to switch blocks in `switch` statements ([§14.11.2](14.11.2.md)) or to switch blocks in `switch` expressions ([§15.28.1](15.28.1.md)).

```
SwitchBlock:
  { SwitchRule {SwitchRule} }
  { {SwitchBlockStatementGroup} {SwitchLabel :} }

SwitchRule:
  SwitchLabel -> Expression ;
  SwitchLabel -> Block
  SwitchLabel -> ThrowStatement

SwitchBlockStatementGroup:
  SwitchLabel : {SwitchLabel :} BlockStatements

SwitchLabel:
  case CaseConstant {, CaseConstant}
  default

CaseConstant:
  ConditionalExpression
```

A switch block can consist of either:

- *Switch rules*, which use `->` to introduce either a *switch rule expression*, a *switch rule block*, or a *switch rule `throw` statement*; or
- *Switch labeled statement groups*, which use `:` to introduce *switch labeled block statements*.

Every switch rule and switch labeled statement group starts with a *switch label*, which is either a `case` label or a `default` label. Multiple switch labels are permitted for a switch labeled statement group.

A `case` label has one or more `case` constants. Every `case` constant must be either a constant expression ([§15.29](15.29.md)) or the name of an enum constant ([§8.9.1](8.9.1.md)), or a compile-time error occurs.

Switch labels and their `case` constants are said to be *associated* with the switch block. No two of the `case` constants associated with a switch block may have the same value, or a compile-time error occurs.

The switch block of a `switch` statement or a `switch` expression is *compatible* with the type of the selector expression, T, if both of the following are true:

- If T is not an enum type, then every `case` constant associated with the switch block is assignment compatible with T ([§5.2](5.2.md)).
- If T is an enum type, then every `case` constant associated with the switch block is an enum constant of type T.

The switch block of a `switch` statement or a `switch` expression must be compatible with the type of the selector expression, or a compile-time error occurs.

Both the execution of a `switch` statement ([§14.11.3](14.11.3.md)) and the evaluation of a `switch` expression ([§15.28.2](15.28.2.md)) need to determine if a switch label *matches* the value of the selector expression. To determine whether a switch label in a switch block matches a given value, the value is compared with the `case` constants associated with the switch block. Then:

- If one of the `case` constants is equal to the value, then we say that the `case` label which contains the `case` constant *matches*.

  Equality is defined in terms of the `==` operator ([§15.21](15.21.md)) unless the value is a `String`, in which case equality is defined in terms of the `equals` method of class `String`.

- If no `case` label matches but there is a `default` label, then we say that the `default` label *matches*.

A `case` label can contain several `case` constants. The label matches the value of the selector expression if any one of its constants matches the value of the selector expression. For example, in the following code, the `case` label matches if the enum variable `day` is either one of the enum constants shown:

```
switch (day) {
    ...
    case SATURDAY, SUNDAY :
        System.out.println("It's the weekend!");
        break;
    ...
}
```

`null` cannot be used as a `case` constant because it is not a constant expression. Even if `case` `null` was allowed, it would be undesirable because the code in that `case` would never be executed. This is due to the fact that, given a selector expression of a reference type (that is, `String` or a boxed primitive type or an enum type), an exception will occur if the selector expression evaluates to `null` at run time. In the judgment of the designers of the Java programming language, propagating the exception is a better outcome than either having no `case` label match, or having the `default` label match.

A Java compiler is encouraged (but not required) to provide a warning if a `switch` statement with an enum-typed selector expression lacks a `default` label and lacks `case` labels for one or more of the enum's constants. Such a `switch` statement will silently do nothing if the expression evaluates to one of the missing constants.

In C and C++ the body of a `switch` statement can be a statement and statements with `case` labels do not have to be immediately contained by that statement. Consider the simple loop:

```
for (i = 0; i < n; ++i) foo();
```

where `n` is known to be positive. A trick known as *Duff's device* can be used in C or C++ to unroll the loop, but this is not valid code in the Java programming language:

```
int q = (n+7)/8;
switch (n%8) {
    case 0: do { foo();    // Great C hack, Tom,
    case 7:      foo();    // but it's not valid here.
    case 6:      foo();
    case 5:      foo();
    case 4:      foo();
    case 3:      foo();
    case 2:      foo();
    case 1:      foo();
            } while (--q > 0);
}
```

Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing compilers.

## 14.11.2. The Switch Block of a `switch` Statement

In addition to the general rules for switch blocks ([§14.11.1](14.11.1.md)), there are further rules for switch blocks in `switch` statements. Namely, all of the following must be true for the switch block of a `switch` statement, or a compile-time error occurs:

- No more than one `default` label is associated with the `switch` block.
- Every switch rule expression in the switch block is a statement expression ([§14.8](14.8.md)).

`switch` statements differ from `switch` expressions in terms of which expressions may appear to the right of an arrow (`->`) in the switch block, that is, which expressions may be used as *switch rule expressions*. In a `switch` statement, only a statement expression may be used as a switch rule expression, but in a `switch` expression, any expression may be used ([§15.28.1](15.28.1.md)).

## 14.11.3. Execution of a `switch` Statement

A `switch` statement is executed by first evaluating the selector expression. Then:

- If evaluation of the selector expression completes abruptly, then the entire `switch` statement completes abruptly for the same reason.
- Otherwise, if the result of evaluating the selector expression is `null`, then a `NullPointerException` is thrown and the entire `switch` statement completes abruptly for that reason.
- Otherwise, if the result of evaluating the selector expression is of type `Character`, `Byte`, `Short`, or `Integer`, it is subjected to unboxing conversion ([§5.1.8](5.1.8.md)). If this conversion completes abruptly, the entire `switch` statement completes abruptly for the same reason.

If evaluation of the selector expression completes normally and the result is non-`null`, and the subsequent unboxing conversion (if any) completes normally, then execution of the `switch` statement continues by determining if a switch label associated with the switch block matches the value of the selector expression ([§14.11.1](14.11.1.md)). Then:

- If no switch label matches, the entire `switch` statement completes normally.

- If a switch label matches, then one of the following applies:

  - If it is the switch label for a switch rule expression, then the switch rule expression is necessarily a statement expression ([§14.11.2](14.11.2.md)). The statement expression is evaluated. If the evaluation completes normally, then the `switch` statement completes normally. If the result of evaluation is a value, it is discarded.
  - If it is the switch label for a switch rule block, then the block is executed. If this block completes normally, then the `switch` statement completes normally.
  - If it is the switch label for a switch rule `throw` statement, then the `throw` statement is executed.
  - If it is the switch label for a switch labeled statement group, then all the statements in the switch block that follow the switch label are executed in order. If these statements complete normally, then the `switch` statement completes normally.
  - Otherwise, there are no statements that follow the matched switch label in the switch block, and the `switch` statement completes normally.

If execution of any statement or expression in the switch block completes abruptly, it is handled as follows:

- If execution of a statement completes abruptly because of a `break` with no label, then no further action is taken and the `switch` statement completes normally.

  Abrupt completion because of a `break` with a label is handled by the general rule for labeled statements ([§14.7](14.7.md)).

- If execution of a statement or expression completes abruptly for any other reason, then the `switch` statement completes abruptly for the same reason.

  Abrupt completion because of a `yield` statement is handled by the general rule for switch expressions ([§15.28.2](15.28.2.md)).

**Example 14.11.3-1. Fall-Through in the `switch` Statement**

When a selector expression matches a switch label for a switch rule, the switch rule expression or statement introduced by the switch label is executed, and nothing else. In the case of a switch label for a statement group, all the block statements in the switch block that follow the switch label are executed, including those that appear after subsequent switch labels. The effect is that, as in C and C++, execution of statements can "fall through labels."

For example, the program:

```
class TooMany {
    static void howMany(int k) {
        switch (k) {
            case 1: System.out.print("one ");
            case 2: System.out.print("too ");
            case 3: System.out.println("many");
        }
    }
    public static void main(String[] args) {
        howMany(3);
        howMany(2);
        howMany(1);
    }
}
```

contains a `switch` block in which the code for each `case` falls through into the code for the next `case`. As a result, the program prints:

```
many
too many
one too many
```

Fall through can be the cause of subtle bugs. If code is not to fall through `case` to `case` in this manner, then `break` statements can be used to indicate when control should be transferred, or switch rules can be used, as in the program:

```
class TwoMany {
    static void howMany(int k) {
        switch (k) {
            case 1: System.out.println("one");
                    break;  // exit the switch
            case 2: System.out.println("two");
                    break;  // exit the switch
            case 3: System.out.println("many");
                    break;  // not needed, but good style
        }
    }
    static void howManyAgain(int k) {
        switch (k) {
            case 1 -> System.out.println("one");
            case 2 -> System.out.println("two");
            case 3 -> System.out.println("many");
        }
    }
    public static void main(String[] args) {
        howMany(1);
        howMany(2);
        howMany(3);
        howManyAgain(1);
        howManyAgain(2);
        howManyAgain(3);
    }
}
```

This program prints:

```
one
two
many
one
two
many
```
