ADocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
switch statement is a multi-way branch control flow construct that evaluates a single expression and transfers execution to a specific block of code associated with a matching case label. At the bytecode level, the Java compiler optimizes switch constructs using tableswitch or lookupswitch instructions, providing constant-time or logarithmic-time branching efficiency compared to sequential if-else-if evaluations.
Supported Data Types
Historically restricted to integral types, theswitch expression target has expanded across Java versions. It currently supports:
- Primitives:
byte,short,char,int - Wrapper Classes:
Byte,Short,Character,Integer - Reference Types:
String(since Java 7),enumtypes - Any Object: via Pattern Matching (since Java 21)
Traditional Syntax (Statement)
The traditionalswitch operates strictly as a statement. It utilizes colon (:) syntax and exhibits fall-through behavior, meaning execution will continue into subsequent case blocks unless explicitly terminated by a break, return, or throw statement.
caselabels must be compile-time constants (finalvariables or literals) of the same type as the evaluated expression.- Duplicate
casevalues result in a compilation error. - The
defaultblock is optional but recommended for exhaustive handling.
Modern Syntax (Expression and Arrow Labels - Java 14+)
Java 14 introducedswitch as an expression (capable of evaluating to a single value) and added the arrow (->) label syntax. The arrow syntax eliminates implicit fall-through; only the block or expression to the right of the arrow is executed.
- Exhaustiveness: A
switchexpression must be exhaustive. The compiler enforces that all possible values of the target type are handled. If the type is not a sealed class or an enum, adefaultclause is mandatory. yieldKeyword: A context-sensitive keyword used to return a value from a full code block{}within aswitchexpression.
Pattern Matching (Java 21+)
Java 21 finalized Pattern Matching forswitch, allowing the construct to evaluate the type of an object, destructure records, and apply boolean guard conditions. The right-hand side of the arrow (->) must be an expression, a block ({}), or a throw statement.
- Dominance:
caselabels are evaluated top-to-bottom. A broader type (e.g.,CharSequence) cannot precede a narrower type (e.g.,String), as it would cause a compilation error due to the narrower case being unreachable. - Null Handling: Prior to Java 21, passing
nullto aswitchimmediately threw aNullPointerException. With pattern matching,case nullcan be explicitly declared to intercept null references safely.
Master Java with Deep Grasping Methodology!Learn More





