Java / Java 21 Coding Standards Interview Questions
Explain the execution flow of a switch expression using guarded patterns?
When a switch expression evaluates its selector, it tests cases top to bottom; a guarded pattern (case Type t when condition ->) only matches if both the type pattern binds successfully and the guard condition evaluates to true, otherwise evaluation falls through to the next case.
flowchart TD
A[Evaluate selector] --> B{Matches case Integer i?}
B -->|no| F{Matches next case}
B -->|yes| C{when i greater than 0?}
C -->|true| D[Execute this branch]
C -->|false| F
F --> G[... continue down cases ...]
Case order therefore matters even with guards: a more specific pattern with a guard should be listed before a broader unguarded pattern of the same type, because once an earlier case's type pattern matches and its guard passes, evaluation stops there and never reaches later cases.
Coding standards ask that guarded cases stay ordered from most to least specific and that the guard expression itself remain a short, side-effect-free boolean check, since a guard hides branching logic behind a condition that is easy to overlook if it grows complex.
More Related questions...