Since Checkstyle 3.2
Checks that local variables that never have their values changed are declared final. The check can be configured to also check that unchanged parameters are declared final.
When configured to check parameters, the check ignores parameters of interface methods and abstract methods.
name | description | type | default value | since |
---|---|---|---|---|
validateEnhancedForLoopVariable | Control whether to check enhanced for-loop variable. | boolean | false |
6.5 |
tokens | tokens to check | subset of tokens VARIABLE_DEF , PARAMETER_DEF . | VARIABLE_DEF . | 3.2 |
To configure the check:
<module name="Checker"> <module name="TreeWalker"> <module name="FinalLocalVariable"/> </module> </module>
To configure the check so that it checks local variables and parameters:
<module name="Checker"> <module name="TreeWalker"> <module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/> </module> </module> </module>
By default, this Check skip final validation on Enhanced For-Loop.
Option 'validateEnhancedForLoopVariable' could be used to make Check to validate even variable from Enhanced For Loop.
An example of how to configure the check so that it also validates enhanced For Loop Variable is:
<module name="Checker"> <module name="TreeWalker"> <module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF"/> <property name="validateEnhancedForLoopVariable" value="true"/> </module> </module> </module>
Example:
for (int number : myNumbers) { // violation System.out.println(number); }
An example of how to configure check on local variables and parameters but do not validate loop variables:
<module name="Checker"> <module name="TreeWalker"> <module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/> <property name="validateEnhancedForLoopVariable" value="false"/> </module> </module> </module>
Example:
public class MyClass { static int foo(int x, int y) { //violations, parameters should be final return x+y; } public static void main (String []args) { //violation, parameters should be final for (String i : args) { System.out.println(i); } int result=foo(1,2); // violation } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.coding