thecodex.expert · The Codex Family of Knowledge
Java

Control Flow

Forgetting a break in a classic switch statement is one of the most notorious bugs in C-family languages — Java’s modern switch expression makes that entire class of mistake impossible.

Java 21 LTS switch expressions (Java 14+) Last verified:
Canonical Definition

if/else, for, while, and do-while follow the same syntax as C, C++, and JavaScript, familiar to anyone coming from those languages. The classic switch statement inherited that same family's fall-through-by-default behavior (a missing break lets execution continue into the next case) — a real, historically common source of bugs. The switch EXPRESSION, finalized in Java 14, uses arrow syntax (->) instead, with no fall-through at all, and can directly produce a value.

if, for, while: familiar C-family syntax

Parentheses around the condition are required (unlike Go or Rust), and braces are optional for single-statement bodies but strongly recommended for clarity.

Javabasic_control_flow.java
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

int n = 0;
while (n < 3) {
    n++;
}

for (String name : List.of("Alice", "Bob")) {   // enhanced for-loop, since Java 5
    System.out.println(name);
}

The classic switch: fall-through by default

A missing break lets execution fall through into the next case unintentionally — legal, compiling code, and a genuine, historically common source of bugs across the whole C-family of languages.

Javaclassic_switch.java
int day = 2;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        // missing break — falls through to case 3!
    case 3:
        System.out.println("Wednesday");
        break;
}
// prints BOTH "Tuesday" and "Wednesday" for day == 2

The modern switch expression: no fall-through, can return a value

Arrow syntax makes each case an isolated block with no fall-through possible, and the whole switch can be used directly as an expression — assigned to a variable, returned, or passed as an argument.

Javaswitch_expression.java
int day = 2;
String name = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";     // no fall-through — each arm is isolated
    case 3 -> "Wednesday";
    default -> "Unknown";
};
System.out.println(name);   // "Tuesday" only

Sources

1
Oracle. The Java Tutorials, "The switch Statement," docs.oracle.com/javase/tutorial, and JEP 361 — Switch Expressions.