Java 21 has introduced enhancements to switch statements and expressions, allowing them to operate on any type, not just specific ones, as in
previous versions. Furthermore, case labels have been upgraded to support patterns, providing an alternative to the previous restriction of only
accepting constants.
// As of Java 21
String patternMatchSwitch(Object obj) {
return switch (obj) {
case String s -> String.format("String %s", s);
case Integer i -> String.format("int %d", i);
default -> obj.toString();
};
}
This allows to use the when
keyword to specify a condition for a case label, also called a guarded case label.
String guardedCaseSwitch(Object obj) {
return switch (obj) {
case String s when s.length() > 0 -> String.format("String %s", s);
case Integer i when i > 0 -> String.format("int %d", i);
default -> obj.toString();
};
}
This syntax is more readable and less error-prone than using an if statement inside the case block and should be preferred.
This rule reports an issue when a single if
statement is used inside a case block.