FinalPatternVariable
Since Checkstyle 14.4.0
Description
Checks that pattern variables that never have their values changed are declared final.
Pattern variables are not implicitly final in Java, and they can be reassigned. This check verifies that pattern variables are explicitly declared as final if they are not reassigned within their flow scope.
Examples
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="FinalPatternVariable"/>
</module>
</module>
Example of violations:
class Example1 {
void method(Object obj) {
// violation below 'Pattern variable 'str' should be declared final.'
if (obj instanceof String str) {
System.out.println(str);
}
if (obj instanceof final String str) {
System.out.println(str);
}
if (obj instanceof String str) {
str = "new value";
System.out.println(str);
}
}
}
Example of Usage
Violation Messages
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Fully Qualified Name
com.puppycrawl.tools.checkstyle.checks.coding.FinalPatternVariableCheck
Use this fully qualified class name in configuration when an exact class reference is required.






