Switch Case Must Terminate

ID

java.switch_case_must_terminate

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:484, code-style, reliability

Description

Reports non-empty case labels in a switch statement that do not end with break, return, throw, continue, or yield. A missing terminator causes implicit fall-through to the next case, which is a frequent source of bugs.

Rationale

Unlike languages that require explicit fall-through syntax, Java switch statements silently continue into the next case when no terminator is present. While intentional fall-through is occasionally useful, the vast majority of missing terminators are bugs. Empty case bodies used for label grouping (case 0: case 1:) are excluded because they represent a deliberate pattern.

This rule flags all non-empty cases without a terminator, including those with a fall-through comment. The complementary rule switch_fallthrough_no_comment only flags cases that both lack a terminator and lack a comment.

switch (day) {
    case MONDAY:
        prepare();
        // missing break -- falls into TUESDAY!
    case TUESDAY:
        work();
        break;
}

Remediation

Add an explicit break, return, throw, or continue to every non-empty case:

switch (day) {
    case MONDAY:
        prepare();
        break;
    case TUESDAY:
        work();
        break;
}

Or use switch expressions (Java 14+) which prevent fall-through entirely:

switch (day) {
    case MONDAY -> prepare();
    case TUESDAY -> work();
}