ArrayTrailingComma

Description

Checks that array initialization contains a trailing comma.

int[] a = new int[]
{
    1,
    2,
    3,
};
        

The check allows leaving out the comma at the end if both the left and right curly brackets are on the same line.

return new int[] { 0 };
        

Rationale: Putting this comma in makes it easier to change the order of the elements or add new elements on the end.

Examples

To configure the check:

<module name="ArrayTrailingComma"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

AvoidInlineConditionals

Description

Detects inline conditionals. Here is one example of an inline conditional:

String a = getParameter("a");
String b = (a==null || a.length<1) ? null : a.substring(1);
        

Rationale: Some developers find inline conditionals hard to read, so their employer's coding standards forbid them.

Examples

To configure the check:

<module name="AvoidInlineConditionals"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

CovariantEquals

Description

Checks that classes that define a covariant equals() method also override method equals(java.lang.Object). Inspired by findbugs.

Rationale: Mistakenly defining a covariant equals() method without overriding method equals(java.lang.Object) can produce unexpected runtime behaviour.

Example

To configure the check:

<module name="CovariantEquals"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

EmptyStatement

Description

Detects empty statements (standalone ";" semicolon).

Examples

To configure the check:

<module name="EmptyStatement"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

EqualsAvoidNull

Description

Checks that any combination of String literals with optional assignment is on the left side of an equals() comparison. The check also processes String.equalsIgnoreCase() invocations (which can be suppressed).

Rationale: Calling the equals() method on String literals will avoid a potential NullPointerException. Also, it is pretty common to see null checks right before equals comparisons, which is not necessary in the example below.

For example, this code:

String nullString = null;
nullString.equals("My_Sweet_String");
        

should be refactored to:

String nullString = null;
"My_Sweet_String".equals(nullString);
        

Limitations: If the equals method is overridden or a covariant equals method is defined and the implementation is incorrect (where s.equals(t) does not return the same result as t.equals(s)) then rearranging the called on object and parameter may have unexpected results.

Java's autoboxing feature affects how this check is implemented. Before Java 5, concatenations of two objects by name would not cause a NullPointerException even if either object is null. Those situations could have been included in this check. They would simply act as if they were surrounded by String.valueOf() which would concatenate the String null.

The following example will cause a NullPointerException as a result of what autoboxing does.

Integer i = null, j = null;
String number = "5"
number.equals(i + j);
        

Since it is difficult to determine what kind of Object is being concatenated, all concatenations of two objects by name are considered unsafe.

Properties

name description type default value
ignoreEqualsIgnoreCase whether to ignore String.equalsIgnoreCase() invocations boolean false

Example

To configure the check:

<module name="EqualsAvoidNull"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

EqualsHashCode

Description

Checks that classes that override equals() also override hashCode().

Rationale: The contract of equals() and hashCode() requires that equal objects have the same hashCode. Therefore, whenever you override equals() you must override hashCode() to ensure that your class can be used in hash-based collections.

Example

To configure the check:

<module name="EqualsHashCode"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

FinalLocalVariable

Description

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.

Notes

When configured to check parameters, the check ignores parameters of interface methods and abstract methods.

Properties

name description type default value
tokens tokens to check subset of tokens PARAMETER_DEF, VARIABLE_DEF VARIABLE_DEF
validateEnhancedForLoopVariable Controls whether to check enhanced for-loop variable. Boolean, false

Examples

To configure the check:

<module name="FinalLocalVariable"/>
        

To configure the check so that it checks local variables and parameters:

<module name="FinalLocalVariable">
    <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/>
</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="FinalLocalVariable">
     <property name="token" value="VARIABLE_DEF"/>
     <property name="validateEnhancedForLoopVariable" value="true"/>
 </module>
         

Example:

         for (int number : myNumbers) { // violation
             System.out.println(number);
         }
         

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

HiddenField

Description

Checks that a local variable or a parameter does not shadow a field that is defined in the same class.

Properties

name description type default value
tokens tokens to check subset of tokens PARAMETER_DEF, VARIABLE_DEF PARAMETER_DEF, VARIABLE_DEF
ignoreFormat pattern for names of variables and parameters to ignore regular expression (not applied)
ignoreConstructorParameter Controls whether to ignore constructor parameters. Boolean false
ignoreSetter Controls whether to ignore the parameter of a property setter method, where the property setter method for field "xyz" has name "setXyz", one parameter named "xyz" and return type of void ( default behavior) or class in which method is declared (only if property setterCanReturnItsClass is set to true). Boolean false
setterCanReturnItsClass Used in conjunction with ignoreSetter property it controls rule that recognizes method as a setter. By default setter is a method with signature of type
                void setXyz(${someType} xyz)
              
By setting this property (setterCanReturnItsClass) to true we expand definition of setter to also include returning class in which setter is defined. For example
                class Foo {
                    int prop;
                    Foo setProp(int prop) {
                        this.prop = prop;
                        return this;
                    }
                }
              
Boolean false
ignoreAbstractMethods Controls whether to ignore parameters of abstract methods. Boolean false

Examples

To configure the check:

<module name="HiddenField"/>
        

To configure the check so that it checks local variables but not parameters:

<module name="HiddenField">
    <property name="tokens" value="VARIABLE_DEF"/>
</module>
        

To configure the check so that it ignores the variables and parameters named "test":

<module name="HiddenField">
    <property name="ignoreFormat" value="^test$"/>
</module>
        
class SomeClass
{
    private List<String> test;

    private void addTest(List<String> test) // no violation
    {
        this.test.addAll(test);
    }

    private void foo()
    {
        final List<String> test = new ArrayList<>(); // no violation
        ...
    }
}
        

To configure the check so that it ignores constructor parameters:

<module name="HiddenField">
    <property name="ignoreConstructorParameter" value="true"/>
</module>
        

To configure the check so that it ignores the parameter of setter methods:

<module name="HiddenField">
    <property name="ignoreSetter" value="true"/>
</module>
        

To configure the check so that it ignores the parameter of setter methods recognizing setter as returning either void or a class in which it is declared:

<module name="HiddenField">
    <property name="ignoreSetter" value="true"/>
    <property name="setterCanReturnItsClass" value="true"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

IllegalInstantiation

Description

Checks for illegal instantiations where a factory method is preferred.

Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.

A simple example is the java.lang.Boolean class. For performance reasons, it is preferable to use the predefined constants TRUE and FALSE. Constructor invocations should be replaced by calls to Boolean.valueOf().

Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools.

Notes

There is a limitation that it is currently not possible to specify array classes.

Properties

name description type default value
classes classes that should not be instantiated String Set {}

Example

To configure the check to find instantiations of java.lang.Boolean:

<module name="IllegalInstantiation">
    <property name="classes" value="java.lang.Boolean"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

IllegalToken

Description

Checks for illegal tokens.

Rational: Certain language features often lead to hard-to-maintain code or are not obvious to novice developers. Other features may be discouraged in certain frameworks, such as not having native methods in Enterprise JavaBeans components.

Properties

name description type default value
tokens tokens to check subset of TokenTypes, LITERAL_SWITCH, POST_INC, POST_DEC

Example

To configure the check to find token LITERAL_NATIVE:

<module name="IllegalToken">
    <property name="tokens" value="LITERAL_NATIVE"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

IllegalTokenText

Description

Checks for illegal token text.

Properties

name description type default value
tokens tokens to check subset of TokenTypes empty
format illegal pattern regular expression ^$ (empty)
ignoreCase Controls whether to ignore case when matching. Boolean false
message Message which is used to notify about violations; if empty then the default message is used. String ""(empty)

Examples

To configure the check to forbid String literals containing "a href":

<module name="IllegalTokenText">
    <property name="tokens" value="STRING_LITERAL"/>
    <property name="format" value="a href"/>
</module>
        

To configure the check to forbid leading zeros in an integer literal, other than zero and a hex literal:

<module name="IllegalTokenText">
    <property name="tokens" value="NUM_INT,NUM_LONG"/>
    <property name="format" value="^0[^lx]"/>
    <property name="ignoreCase" value="true"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

InnerAssignment

Description

Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.

Rationale: With the exception of for iterators, all assignments should occur in their own top-level statement to increase readability. With inner assignments like the one given above, it is difficult to see all places where a variable is set.

Properties

name description type default value
tokens assignments to check subset of tokens ASSIGN, BAND_ASSIGN, BOR_ASSIGN, BSR_ASSIGN, BXOR_ASSIGN, DIV_ASSIGN, MINUS_ASSIGN, MOD_ASSIGN, PLUS_ASSIGN, SL_ASSIGN, SR_ASSIGN, STAR_ASSIGN all tokens

Examples

To configure the check:

<module name="InnerAssignment"/>
        

To configure the check for only =, +=, and -= operators:

<module name="InnerAssignment">
    <property name="tokens" value="ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

MagicNumber

Description

Checks that there are no "magic numbers", where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.

Properties

name description type default value
tokens tokens to check subset of tokens NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG all tokens
ignoreNumbers non-magic numbers list of numbers -1, 0, 1, 2
ignoreHashCodeMethod ignore magic numbers in hashCode methods boolean false
ignoreAnnotation ignore magic numbers in annotation declarations. boolean false

Examples

To configure the check:

<module name="MagicNumber"/>
        

To configure the check so that it checks floating-point numbers that are not 0, 0.5, or 1:

<module name="MagicNumber">
    <property name="tokens" value="NUM_DOUBLE, NUM_FLOAT"/>
    <property name="ignoreNumbers" value="0, 0.5, 1"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

MissingSwitchDefault

Description

Checks that switch statement has a "default" clause.

Rationale: It's usually a good idea to introduce a default case in every switch statement. Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch, e.g. by using an assertion. This way the code is protected against later changes, e.g. introduction of new types in an enumeration type.

Examples

To configure the check:

<module name="MissingSwitchDefault"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

ModifiedControlVariable

Description

Check for ensuring that for loop control variables are not modified inside the for block. An example is:

for (int i = 0; i < 1; i++) {
    i++;
}
        

Rationale: If the control variable is modified inside the loop body, the program flow becomes more difficult to follow. An option is to replace the for loop with a while loop.

Example

To configure the check:

<module name="ModifiedControlVariable"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

SimplifyBooleanExpression

Description

Checks for over-complicated boolean expressions. Currently finds code like if (b == true), b || true, !false, etc.

Rationale: Complex boolean logic makes code hard to understand and maintain.

Example

To configure the check:

<module name="SimplifyBooleanExpression"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

SimplifyBooleanReturn

Description

Checks for over-complicated boolean return statements. For example the following code

if (valid())
    return false;
else
    return true;
        

could be written as

return !valid();
        

The idea for this Check has been shamelessly stolen from the equivalent PMD rule.

Example

To configure the check:

<module name="SimplifyBooleanReturn"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

StringLiteralEquality

Description

Checks that string literals are not used with == or !=.

Rationale: Novice Java programmers often use code like:

if (x == "something")
        

when they mean

if ("something".equals(x))
        

Example

To configure the check:

<module name="StringLiteralEquality"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

NestedForDepth

Description

Restricts nested for blocks to a specified depth (default = 1).

Properties

name description type default value
max allowed nesting depth Integer 1

Example

To configure the check:

<module name="NestedForDepth"/>
        

To configure the check to allow nesting depth 3:

<module name="NestedForDepth">
    <property name="max" value="3"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

NestedIfDepth

Description

Restricts nested if-else blocks to a specified depth (default = 1).

Properties

name description type default value
max allowed nesting depth Integer 1

Example

To configure the check:

<module name="NestedIfDepth"/>
        

To configure the check to allow nesting depth 3:

<module name="NestedIfDepth">
    <property name="max" value="3"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

NestedTryDepth

Description

Restricts nested try blocks to a specified depth (default = 1).

Properties

name description type default value
max allowed nesting depth Integer 1

Example

To configure the check:

<module name="NestedTryDepth"/>
        

To configure the check to allow nesting depth 3:

<module name="NestedTryDepth">
    <property name="max" value="3"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

NoClone

Description

Checks that the clone method is not overridden from the Object class.

Rationale: The clone method relies on strange, hard to follow rules that are difficult to get right and do not work in all situations. In some cases, either a copy constructor or a static factory method can be used instead of the clone method to return copies of an object. For more information on rules for the clone method and its issues, see Effective Java: Programming Language Guide First Edition by Joshua Bloch pages 45-52.

This check is almost exactly the same as the {@link NoFinalizerCheck}

Example

To configure the check:

<module name="NoClone"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

NoFinalizer

Description

Verifies there are no finalize() methods defined in a class.

Example

To configure the check:

<module name="NoFinalizer"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

SuperClone

Description

Checks that an overriding clone() method invokes super.clone().

Reference: Object.clone().

Examples

To configure the check:

<module name="SuperClone"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

SuperFinalize

Description

Checks that an overriding finalize() method invokes super.finalize().

Reference: Use Finalization Only When You Must.

Examples

To configure the check:

<module name="SuperFinalize"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

IllegalCatch

Description

Checks that certain exception types do not appear in a catch statement.

Rationale: Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable. Novice developers often simply catch Exception in an attempt to handle multiple exception classes. This unfortunately leads to code that inadvertently catches NullPointerException, OutOfMemoryError, etc.

Properties

name description type default value
illegalClassNames exception class names to reject list of strings "java.lang.Exception, java.lang.Throwable, java.lang.RuntimeException"

Examples

To configure the check:

<module name="IllegalCatch"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

IllegalThrows

Description

This check can be used to ensure that types are not declared to be thrown. Declaring that a method throws java.lang.Error or java.lang.RuntimeException is almost never acceptable.

Properties

name description type default value
illegalClassNames throw class names to reject list of strings "java.lang.Throwable, java.lang.Error, java.lang.RuntimeException"
ignoredMethodNames names of methods to ignore list of strings finalize
ignoreOverriddenMethods ignore checking overridden methods (marked with Override or java.lang.Override annotation). Boolean true

Examples

To configure the check:

<module name="IllegalThrows"/>
        

To configure the check rejecting throws NullPointerException from methods:

<module name="IllegalThrows">
    <property name="illegalClassNames" value="NullPointerException"/>
</module>
        

To configure the check ignoring method named "foo()":

<module name="IllegalThrows">
    <property name="ignoredMethodNames" value="foo"/>
</module>
        

To configure the check to warn on overridden methods:

<module name="IllegalThrows">
    <property name="ignoreOverriddenMethods" value="false"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

PackageDeclaration

Description

Ensures that a class has a package declaration, and (optionally) whether the package name matches the directory name for the source file.

Rationale: Classes that live in the null package cannot be imported. Many novice developers are not aware of this.

Examples

To configure the check:

<module name="PackageDeclaration"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

ReturnCount

Description

Restricts the number of return statements (2 by default). Ignores specified methods (equals() by default).

Rationale: Too many return points can mean that code is attempting to do too much or may be difficult to understand.

Properties

name description type default value
max maximum allowed number of return statements Integer 2
format method names to ignore regular expression ^equals$ (empty)

Examples

To configure the check so that it doesn't allow more than three return statements per method (ignoring the equals() method):

<module name="ReturnCount">
    <property name="max" value="3"/>
</module>
        

To configure the check so that it doesn't allow more than three return statements per method for all methods:

<module name="ReturnCount">
    <property name="max" value="3"/>
    <property name="format" value="^$"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

IllegalType

Description

Checks that particular classes are never used as types in variable declarations, return values or parameters. Includes a pattern check that by default disallows abstract classes.

Rationale: Helps reduce coupling on concrete classes. In addition abstract classes should be thought of as convenient base class implementations of interfaces, and as such, are not types themselves.

Properties

name description type default value
tokens tokens to check subset of tokens PARAMETER_DEF, VARIABLE_DEF METHOD_DEF PARAMETER_DEF, VARIABLE_DEF METHOD_DEF
illegalClassNames Classes that should not be used as types in variable declarations, return values or parameters String Set "java.util.HashSet, java.util.HashMap, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.TreeSet, java.util.TreeMap"
legalAbstractClassNames Abstract classes that may be used as types. String Set
ignoredMethodNames Methods that should not be checked. String Set "getInitialContext, getEnvironment"
format Pattern for illegal class names. regular expression ^(.*[\\.])?Abstract.*$
memberModifiers Check methods and fields with only corresponding modifiers. List of tokens null

Examples

To configure the check so that it ignores getInstance() methods:

<module name="IllegalType">
    <property name="ignoredMethodNames" value="getInstance"/>
</module>
        

To configure the Check so that it verifies only public, protected and static methods and fields:

<module name="IllegalType">
    <property name="memberModifiers" value="LITERAL_PUBLIC,
     LITERAL_PROTECTED, LITERAL_STATIC"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

DeclarationOrder

Description

According to Code Conventions for the Java Programming Language , the parts of a class or interface declaration should appear in the following order:

  1. Class (static) variables. First the public class variables, then protected, then package level (no access modifier), and then private.
  2. Instance variables. First the public class variables, then protected, then package level (no access modifier), and then private.
  3. Constructors
  4. Methods

Properties

name description type default value
ignoreConstructors whether to ignore constructors Boolean false
ignoreMethods whether to ignore methods Boolean false
ignoreModifiers whether to ignore modifiers Boolean false

Examples

To configure the check:

<module name="DeclarationOrder"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

ParameterAssignment

Description

Disallows assignment of parameters.

Rationale: Parameter assignment is often considered poor programming practice. Forcing developers to declare parameters as final is often onerous. Having a check ensure that parameters are never assigned would give the best of both worlds.

Examples

To configure the check:

<module name="ParameterAssignment"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

ExplicitInitialization

Description

Checks if any class or object member is explicitly initialized to default for its type value (null for object references, zero for numeric types and char and false for boolean.

Rationale: Each instance variable gets initialized twice, to the same value. Java initializes each instance variable to its default value (0 or null) before performing any initialization specified in the code. So in this case, x gets initialized to 0 twice, and bar gets initialized to null twice. So there is a minor inefficiency. This style of coding is a holdover from C/C++ style coding, and it shows that the developer isn't really confident that Java initializes instance variables to default values.

Examples

To configure the check:

<module name="ExplicitInitialization"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

DefaultComesLast

Description

Check that the default is after all the cases in a switch statement.

Rationale: Java allows default anywhere within the switch statement. But it is more readable if it comes after the last case.

Examples

To configure the check:

<module name="DefaultComesLast"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

MissingCtor

Description

Checks that classes (except abstract ones) define a constructor and don't rely on the default one.

Examples

To configure the check:

<module name="MissingCtor"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

FallThrough

Description

Checks for fall-through in switch statements. Finds locations where a case contains Java code but lacks a break, return, throw or continue statement.

The check honors special comments to suppress the warning. By default the text "fallthru", "fall through", "fallthrough", "falls through" and "fallsthrough" are recognized (case sensitive). The comment containing these words must be all on one line, and must be on the last non-empty line before the case triggering the warning or on the same line before the case (ugly, but possible).

switch (i){
case 0:
    i++; // fall through

case 1:
    i++;
    // falls through
case 2: {
    i++;
}
// fallthrough
case 3:
    i++;
/* fallthru */case 4:
    i++
    break;
}
        

Note: The check assumes that there is no unreachable code in the case.

Properties

name description type default value
checkLastCaseGroup Whether the last case group must be checked. Boolean false
reliefPattern Regular expression to match the relief comment that suppresses the warning about a fall through. regular expression fallthru|falls? ?through

Examples

To configure the check:

<module name="FallThrough"/>
        

or

<module name="FallThrough">
    <property name="reliefPattern" value="continue in next case"/>
<module name="FallThrough"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

MultipleStringLiterals

Description

Checks for multiple occurrences of the same string literal within a single file.

Rationale: Code duplication makes maintenance more difficult, so it can be better to replace the multiple occurrences with a constant.

Properties

name description type default value
allowedDuplicates The maximum number of occurrences to allow without generating a warning Integer 1
ignoreStringsRegexp Regular expression pattern for ignored strings (with quotation marks) regular expression ^""$ (ignore empty strings)
ignoreOccurrenceContext Token type names where duplicate strings are ignored even if they don't match ignoredStringsRegexp. This allows you to exclude syntactical contexts like annotations or static initializers from the check. list of token type names ANNOTATION (ignore strings inside the context of an annotation)

Examples

To configure the check:

<module name="MultipleStringLiterals"/>
        

To configure the check so that it allows two occurrences of each string:

<module name="MultipleStringLiterals">
    <property name="allowedDuplicates" value="2"/>
</module>
        

To configure the check so that it ignores ", " and empty strings:

<module name="MultipleStringLiterals">
    <property name="ignoreStringsRegexp" value='^(("")|(", "))$'/>
</module>
        

To configure the check so that it flags duplicate strings in all syntactical contexts, even in annotations like @SuppressWarnings("unchecked"):

<module name="MultipleStringLiterals">
    <property name="ignoreOccurrenceContext" value=""/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

MultipleVariableDeclarations

Description

Checks that each variable declaration is in its own statement and on its own line.

Rationale: the Java code conventions chapter 6.1 recommends that declarations should be one per line/statement.

Examples

To configure the check:

<module name="MultipleVariableDeclarations"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

RequireThis

Description

Checks that references to instance variables and methods of the present object are explicitly of the form "this.varName" or "this.methodName(args)" and that those references don't rely on the default behavior when "this." is absent.

Properties

name description type default value
checkFields Whether to check references to fields. boolean true
checkMethods Whether to check references to methods. boolean true

Examples

To configure the default check:

<module name="RequireThis"/>
        

To configure to check the this qualifier for fields only:

<module name="RequireThis">
    <property name="checkMethods" value="false"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

UnnecessaryParentheses

Description

Checks for the use of unnecessary parentheses.

Examples

To configure the check:

<module name="UnnecessaryParentheses"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

OneStatementPerLine

Description

Checks that there is only one statement per line. The following line will be flagged as an error:

    x = 1; y = 2; // Two statements on a single line.

Examples

To configure the check:

<module name="OneStatementPerLine"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

VariableDeclarationUsageDistance

Description

Checks the distance between declaration of variable and its first usage.

Properties

name description type default value
allowedDistance A distance between declaration of variable and its first usage integer 3
ignoreVariablePattern pattern for ignoring the distance calculation regular expression (not applied)
validateBetweenScopes Allows to calculate the distance between declaration of variable and its first usage in the different scopes. Boolean false
ignoreFinal Allows to ignore variables with a 'final' modifier. Boolean true

Examples

Example #1:

int count;
a = a + b;
b = a + a;
count = b; // DECLARATION OF VARIABLE 'count'
           // SHOULD BE HERE (distance = 3)
        

Example #2:

int count;
{
     a = a + b;
     count = b; // DECLARATION OF VARIABLE 'count'
                // SHOULD BE HERE (distance = 2)
}
        

Check can detect a block of initialization methods. If a variable is used in such a block and there is no other statements after this variable then distance=1.

Case #1:

int minutes = 5;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeNow);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.HOUR_OF_DAY, hh);
cal.set(Calendar.MINUTE, minutes);
        

The distance for the variable minutes is 1 even though this variable is used in the fifth method's call.

Case #2:

int minutes = 5;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeNow);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(cal);
cal.set(Calendar.HOUR_OF_DAY, hh);
cal.set(Calendar.MINUTE, minutes);
         

The distance for the variable minutes is 6 because there is one more expression (except the initialization block) between the declaration of this variable and its usage.

An example how to configure this Check:

<module name="VariableDeclarationUsageDistance"/>
         

An example of how to configure this Check: - to set the allowed distance to 4; - to ignore variables with prefix '^temp'; - to force the validation between scopes; - to check the final variables;

<module name="VariableDeclarationUsageDistance">
    <property name="allowedDistance" value="4">
    <property name="ignoreVariablePattern" value="^temp.*">
    <property name="validateBetweenScopes" value="true">
    <property name="mIgnoreFinal" value="false">
</module>
         

Note

ATTENTION!! (Not supported cases)

 Case #1:
 {
 int c;
 int a = 3;
 int b = 2;
     {
     a = a + b;
     c = b;
     }
 }
        

Distance for variable 'a' = 1; Distance for variable 'b' = 1; Distance for variable 'c' = 2.

As distance by default is 1 the Check doesn't raise warning for variables 'a' and 'b' to move them into the block.

Case #2:

 int sum = 0;
 for (int i = 0; i < 20; i++) {
     a++;
     b--;
     sum++;
     if (sum > 10) {
         res = true;
     }
 }
         

Distance for variable 'sum' = 3.

As the distance is more then the default one, the Check raises warning for variable 'sum' to move it into the 'for(...)' block. But there is situation when variable 'sum' hasn't to be 0 within each iteration. So, to avoid such warnings you can use Suppression Filter, provided by Checkstyle, for the whole class.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker

OverloadMethodsDeclarationOrder

Description

Checks that overload methods are grouped together.

Examples

Example of incorrect grouping overload methods:

public void foo(int i) {}
public void foo(String s) {}
public void notFoo() {} // Have to be after foo(int i, String s)
public void foo(int i, String s) {}
        

An example of how to configure the check is:

<module name="OverloadMethodsDeclarationOrder"/>
        

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker