Java / Java 21 Coding Standards Interview Questions
How do you format a pattern-matching switch expression per Java 21 coding standards?
A pattern-matching switch is written as an expression using arrow syntax, with each case testing a type pattern rather than a constant, and the result assigned directly instead of through a mutable local variable.
String describe(Object obj) { return switch (obj) { case Integer i when i > 0 -> "positive integer"; case Integer i -> "non-positive integer"; case String s -> "string of length " + s.length(); case null -> "null value"; default -> "unknown"; }; }
Standards require pattern variables to be named descriptively rather than reused generic names like o, guard conditions introduced with when to stay short enough to read on one line, and a default branch present unless the type being switched on is sealed and every permitted subtype is already covered, in which case the compiler enforces exhaustiveness on its own.
More Related questions...