LocalFinalVariableName

Since Checkstyle 3.0

Description

Checks that local final variable names conform to a specified pattern. A catch parameter and resources in try statements are considered to be a local, final variables.

This check does not support final pattern variables. Instead, use PatternVariableName.

Properties

name description type default value since
format Sets the pattern to match valid identifiers. Pattern "^([a-z][a-zA-Z0-9]*|_)$" 3.0
tokens tokens to check subset of tokens VARIABLE_DEF , PARAMETER_DEF , RESOURCE . VARIABLE_DEF , PARAMETER_DEF , RESOURCE . 3.0

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="LocalFinalVariableName">
       <property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
    </module>
  </module>
</module>
        

Code Example:

class Example1{
  void MyMethod() {
    try {
      final int VAR1 = 5; // violation
      final int var1 = 10;
    } catch (Exception ex) {
      final int VAR2 = 15; // violation
      final int var2 = 20;
    }
  }
}
        

An example of how to configure the check for names that are only upper case letters and digits is:

<module name="Checker">
  <module name="TreeWalker">
    <module name="LocalFinalVariableName">
      <property name="format" value="^[A-Z][A-Z0-9]*$"/>
    </module>
  </module>
</module>
        

Code Example:

class Example2 {
  void MyMethod() {
    try {
      final int VAR1 = 5;
      final int var1 = 10; // violation
    } catch (Exception ex) {
      final int VAR2 = 15;
      final int var2 = 20; // violation
    }
  }
}
        

An example of how to configure the check for names of local final parameters and resources in try statements (without checks on variables):

<module name="Checker">
  <module name="TreeWalker">
    <module name="LocalFinalVariableName">
      <property name="format" value="^[A-Z][A-Z0-9]*$"/>
      <property name="tokens" value="PARAMETER_DEF,RESOURCE"/>
    </module>
  </module>
</module>
        

Code Example:

class Example3 {
  void MyMethod() {
    try(Scanner scanner = new Scanner(System.in)) { // violation

      final int VAR1 = 5;
      final int var1 = 10;
    } catch (final Exception ex) { // violation

      final int VAR2 = 15;
      final int var2 = 20;
    }
  }
}
        

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.

Package

com.puppycrawl.tools.checkstyle.checks.naming

Parent Module

TreeWalker