Since Checkstyle 3.2
Checks that array initialization contains a trailing comma.
int[] a = new int[] { 1, 2, 3, };
The check demands a comma at the end if neither left nor right curly braces are on the same line as the last element of the array.
return new int[] { 0 }; return new int[] { 0 }; 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. Main benefit of a trailing comma is that when you add new entry to an array, no surrounding lines are changed.
{ 100000000000000000000, 200000000000000000000, // OK } { 100000000000000000000, 200000000000000000000, 300000000000000000000, // Just this line added, no other changes }
If closing brace is on the same line as training comma, this benefit is gone (as the Check does not demand a certain location of curly braces the following two cases will not produce a violation):
{100000000000000000000, 200000000000000000000,} // Trailing comma not needed, line needs to be modified anyway {100000000000000000000, 200000000000000000000, // Modified line 300000000000000000000,} // Added line
If opening brace is on the same line as training comma there's also (more arguable) problem:
{100000000000000000000, // Line cannot be just duplicated to slightly modify entry } {100000000000000000000, 100000000000000000001, // More work needed to duplicate }
To configure the check:
<module name="ArrayTrailingComma"/>
Which results in the following violations:
int[] numbers = {1, 2, 3}; //no violation boolean[] bools = { true, true, false }; //violation String[][] text = {{},{},}; //no violation double[][] decimals = { {0.5, 2.3, 1.1,}, //no violation {1.7, 1.9, 0.6}, {0.8, 7.4, 6.5} }; // violation as previous line misses a comma char[] chars = {'a', 'b', 'c' }; / /no violation String[] letters = { "a", "b", "c"}; // no violation int[] a1 = new int[]{ 1, 2 , }; // no violation int[] a2 = new int[]{ 1, 2 ,}; // no violation
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.1
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Checks that classes which define a covariant equals() method
also override method equals(Object).
Covariant equals() - method that is similar to equals(Object),
but with a covariant parameter type (any subtype of Object).
Notice: the enums are also checked, even
though they cannot override equals(Object). The reason is
to point out that implementing equals() in enums is considered an
awful practice: it may cause having two different enum values that are equal using
covariant enum method, and not equal when compared normally.
Inspired by Finding Bugs is Easy, chapter '2.3.1 Bad Covariant Definition of Equals (Eq)':
Java classes may override the equals(Object) method to define a predicate for object equality. This method is used by many of the Java runtime library classes; for example, to implement generic containers.
Programmers sometimes mistakenly use the type of their class Foo as the type of the parameter to equals():
public boolean equals(Foo obj) {...}
This covariant version of equals() does not override the version in the Object class, and it may lead to unexpected behavior at runtime, especially if the class is used with one of the standard collection classes which expect that the standard equals(Object) method is overridden.
This kind of bug is not obvious because it looks correct, and in circumstances where the class is accessed through the references of the class type (rather than a supertype), it will work correctly. However, the first time it is used in a container, the behavior might be mysterious. For these reasons, this type of bug can elude testing and code inspections.
To configure the check:
<module name="CovariantEquals"/>
For example:
class Test { public boolean equals(Test i) { // violation return false; } }
The same class without violations:
class Test { public boolean equals(Test i) { // no violation return false; } public boolean equals(Object i) { return false; } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
According to Code Conventions for the Java Programming Language , the parts of a class or interface declaration should appear in the following order:
Purpose of ignore* option is to ignore related violations, however it still impacts on other class members.
ATTENTION: the check skips class fields which have forward references from validation due to the fact that we have Checkstyle's limitations to clearly detect user intention of fields location and grouping. For example,
public class A { private double x = 1.0; private double y = 2.0; public double slope = x / y; // will be skipped from validation due to forward reference }
name | description | type | default value | since |
---|---|---|---|---|
ignoreConstructors | whether to ignore constructors | Boolean | false | 5.2 |
ignoreModifiers | whether to ignore modifiers | Boolean | false | 5.2 |
To configure the check:
<module name="DeclarationOrder"/>
For example:
class K { int a; void m(){} K(){} <-- "Constructor definition in wrong order" int b; <-- "Instance variable definition in wrong order" }
With ignoreConstructors option:
class K { int a; void m(){} K(){} int b; <-- "Instance variable definition in wrong order" }
With ignoreConstructors option and without a method definition in a source class:
class K { int a; K(){} int b; <-- "Instance variable definition in wrong order" }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.4
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.
name | description | type | default value | since |
---|---|---|---|---|
skipIfLastAndSharedWithCase | whether to allow default along with case if they are not last | Boolean | false | 7.7 |
To configure the check:
<module name="DefaultComesLast"/>
To configure the check for skipIfLastAndSharedWithCase:
<module name="DefaultComesLast"> <property name="skipIfLastAndSharedWithCase" value="true"/> </module>
Example when skipIfLastAndSharedWithCase is set to true.
switch (i) { case 1: break; case 2: default: // No violation with the new option is expected break; case 3: break; } switch (i) { case 1: break; default: // violation with the new option is expected case 2: break; }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 5.0
Checks that any combination of String literals is on the left side of an equals() comparison. Also checks for String literals assigned to some field (such as someString.equals(anotherString = "text")).
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);
name | description | type | default value | since |
---|---|---|---|---|
ignoreEqualsIgnoreCase | whether to ignore String.equalsIgnoreCase() invocations | Boolean | false | 5.4 |
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.0
Checks that classes that either override equals() or hashCode() also overrides the other. This checks only verifies that the method declarations match Object.equals(Object)} and Object.hashCode() exactly to be considered an override. This check does not verify invalid method names, parameters other than Object, or anything else.
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
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.
name | description | type | default value | since |
---|---|---|---|---|
onlyObjectReferences | whether only explicit initializations made to null for objects should be checked | Boolean | false | 7.8 |
To configure the check:
<module name="ExplicitInitialization"/>
To configure the check so that it only checks for objects that explicitly initialize to null:
<module name="ExplicitInitialization"> <property name="onlyObjectReferences" value="true"/> </module>
Example:
public class Test { private int a = 0; private int b = 1; private int c = 2; private boolean a = true; private boolean b = false; private boolean c = true; private boolean d = false; private boolean e = false; private A a = new A(); private A b = null; // violation private C c = null; // violation private D d = new D(); int ar1[] = null; // violation int ar2[] = new int[]; int ar3[]; private Bar<String> bar = null; // violation private Bar<String>[] barArray = null; // violation public static void main( String [] args ) { } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.4
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: case 3: case 4: { i++; } // fallthrough case 5: i++; /* fallthru */case 6: i++ break; }
Note: The check assumes that there is no unreachable code in the case.
name | description | type | default value | since |
---|---|---|---|---|
checkLastCaseGroup | Whether the last case group must be checked. | Boolean | false | 4.0 |
reliefPattern | Regular expression to match the relief comment that suppresses the warning about a fall through. | Regular Expression | "fallthru|falls? ?through" | 4.0 |
To configure the check:
<module name="FallThrough"/>
or
<module name="FallThrough"> <property name="reliefPattern" value="continue in next case"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
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 | Controls 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="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="tokens" value="VARIABLE_DEF"/> <property name="validateEnhancedForLoopVariable" value="true"/> </module>
Example:
for (int number : myNumbers) { // violation System.out.println(number); }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.0
Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
name | description | type | default value | since |
---|---|---|---|---|
ignoreFormat | pattern for names of variables and parameters to ignore | Regular Expression | null | 3.2 |
ignoreConstructorParameter | Controls whether to ignore constructor parameters. | Boolean | false | 3.2 |
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 | 3.2 |
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) class Foo { int prop; Foo setProp(int prop) { this.prop = prop; return this; } } |
Boolean | false | 6.3 |
ignoreAbstractMethods | Controls whether to ignore parameters of abstract methods. | Boolean | false | 4.0 |
tokens | tokens to check | subset of tokens VARIABLE_DEF, PARAMETER_DEF, LAMBDA. | VARIABLE_DEF, PARAMETER_DEF, LAMBDA. | 3.0 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
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.
name | description | type | default value | since |
---|---|---|---|---|
illegalClassNames | exception class names to reject | String Set | java.lang.Throwable, RuntimeException, Error, Throwable, java.lang.Error, java.lang.RuntimeException, Exception, java.lang.Exception | 3.2 |
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.0
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.
name | description | type | default value | since |
---|---|---|---|---|
classes | classes that should not be instantiated | String Set | {} | 3.0 |
tokens | tokens to check | subset of tokens CLASS_DEF. | CLASS_DEF. | 3.0 |
To configure the check to find instantiations of java.lang.Boolean:
<module name="IllegalInstantiation"> <property name="classes" value="java.lang.Boolean"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 4.0
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.
name | description | type | default value | since |
---|---|---|---|---|
illegalClassNames | throw class names to reject | String Set | java.lang.Throwable, RuntimeException, Error, Throwable, java.lang.Error, java.lang.RuntimeException | 4.0 |
ignoredMethodNames | names of methods to ignore | String Set | finalize | 5.4 |
ignoreOverriddenMethods | ignore checking overridden methods (marked with Override or java.lang.Override annotation). | Boolean | true | 6.4 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Checks for illegal tokens. By default labels are prohibited.
Rationale: Certain language features can harm readability, lead to confusion 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.
name | description | type | default value | since |
---|---|---|---|---|
tokens | tokens to check | subset of tokens TokenTypes. | LABELED_STAT. | 3.2 |
To configure the check to find token LITERAL_NATIVE:
<module name="IllegalToken"> <property name="tokens" value="LITERAL_NATIVE"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Checks specified tokens text for matching an illegal pattern from format property. By default no tokens are specified.
name | description | type | default value | since |
---|---|---|---|---|
format | illegal pattern | Regular Expression | "$^" (empty) | 3.2 |
ignoreCase | Controls whether to ignore case when matching. | Boolean | false | 3.2 |
message | Message which is used to notify about violations; if empty then the default message is used. | String | "" | 3.2 |
tokens | tokens to check | subset of tokens NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG, IDENT, COMMENT_CONTENT, STRING_LITERAL, CHAR_LITERAL. | empty | 3.2 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Checks that particular classes are never used as types in variable declarations, one-dimensional and multi-dimensional arrays, return values or parameters.
Rationale: Helps reduce coupling on concrete classes.
For additional restriction of type usage see also: IllegalInstantiation, IllegalImport
name | description | type | default value | since |
---|---|---|---|---|
validateAbstractClassNames | Whether to validate abstract class names | Boolean | false | 6.10 |
illegalClassNames | Classes that should not be used as types in variable declarations, return values or parameters | String Set | LinkedHashSet, java.util.HashSet, java.util.LinkedHashMap, java.util.TreeMap, HashMap, TreeSet, java.util.HashMap, TreeMap, java.util.LinkedHashSet, java.util.TreeSet, HashSet, LinkedHashMap | 3.2 |
legalAbstractClassNames | Abstract classes that may be used as types. | String Set | {} | 4.2 |
ignoredMethodNames | Methods that should not be checked. | String Set | getInitialContext, getEnvironment | 3.2 |
format | Pattern for illegal class names. | Regular Expression | "^(.*[.])?Abstract.*$" | 3.2 |
memberModifiers | Check methods and fields with only corresponding modifiers. | subset of tokens TokenTypes | 6.3 | |
tokens | tokens to check | subset of tokens VARIABLE_DEF, PARAMETER_DEF, METHOD_DEF. | VARIABLE_DEF, PARAMETER_DEF, METHOD_DEF. | 3.2 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.0
Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.
Rationale: With the exception of for iterators and assignment in while idiom, 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.
Note: Check allows usage of the popular assignment in while idiom:
String line; while ((line = bufferedReader.readLine()) != null) { // process the line }
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.1
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.
It is fine to have one constant defining multiple numeric literals within one expression:
static final int SECONDS_PER_DAY = 24 * 60 * 60; static final double SPECIAL_RATIO = 4.0 / 3.0; static final double SPECIAL_SUM = 1 + Math.E; static final double SPECIAL_DIFFERENCE = 4 - Math.PI; static final Border STANDARD_BORDER = BorderFactory.createEmptyBorder(3, 3, 3, 3); static final Integer ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE = new Integer(42);
name | description | type | default value | since |
---|---|---|---|---|
ignoreNumbers | non-magic numbers | Number Set | -1, 0, 1, 2 | 3.1 |
ignoreHashCodeMethod | ignore magic numbers in hashCode methods | Boolean | false | 5.3 |
ignoreAnnotation | ignore magic numbers in annotation declarations. | Boolean | false | 5.4 |
ignoreFieldDeclaration | ignore magic numbers in field declarations. | Boolean | false | 6.6 |
constantWaiverParentToken | Token that are allowed in the AST path from the number literal to the enclosing constant definition. | subset of tokens TokenTypes | TYPECAST, METHOD_CALL, EXPR, ARRAY_INIT, UNARY_MINUS, UNARY_PLUS, ELIST, STAR, ASSIGN, PLUS, MINUS, DIV, LITERAL_NEW | 6.11 |
tokens | tokens to check | subset of tokens NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG. | NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG. | 3.1 |
To configure the check with default configuration:
<module name="MagicNumber"/>
results is following violations:
@MyAnnotation(6) // violation class MyClass { private field = 7; // violation void foo() { int i = i + 1; // no violation int j = j + 8; // violation } }
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"/> <property name="ignoreFieldDeclaration" value="true"/> <property name="ignoreAnnotation" value="true"/> </module>
results is following violations:
@MyAnnotation(6) // no violation class MyClass { private field = 7; // no violation void foo() { int i = i + 1; // no violation int j = j + 8; // violation } }
Config Example for constantWaiverParentToken Option:
<module name="MagicNumber"> <property name="constantWaiverParentToken" value="ASSIGN,ARRAY_INIT,EXPR, UNARY_PLUS, UNARY_MINUS, TYPECAST, ELIST, DIV, PLUS "/> </module>
result is following violation:
class TestMethodCall { public void method2() { final TestMethodCall dummyObject = new TestMethodCall(62); //violation final int a = 3; // ok as waiver is ASSIGN final int [] b = {4, 5} // ok as waiver is ARRAY_INIT final int c = -3; // ok as waiver is UNARY_MINUS final int d = +4; // ok as waiver is UNARY_PLUS final int e = method(1, 2) // ELIST is there but violation due to METHOD_CALL final int x = 3 * 4; // violation final int y = 3 / 4; // ok as waiver is DIV final int z = 3 + 4; // ok as waiver is PLUS final int w = 3 - 4; // violation final int x = (int)(3.4); //ok as waiver is TYPECAST } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.4
Checks that classes (except abstract ones) define a constructor and don't rely on the default one.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.1
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.5
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++; //violation }
Rationale: If the control variable is modified inside the loop
body, the program flow becomes more difficult to follow.
See FOR statement specification for more details.
Such loop would be suppressed:
for (int i = 0; i < 10;) { i++; }
name | description | type | default value | since |
---|---|---|---|---|
skipEnhancedForLoopVariable | Controls whether to check enhanced for-loop variable. | Boolean | false | 6.8 |
To configure the check:
<module name="ModifiedControlVariable"/>
By default, This Check validates Enhanced For-Loop.
Option 'skipEnhancedForLoopVariable' could be used to skip check of variable from Enhanced For Loop.
An example of how to configure the check so that it skips enhanced For Loop Variable is:
<module name="ModifiedControlVariable"> <property name="skipEnhancedForLoopVariable" value="true"/> </module>
Example:
for ( String line: lines ) { line = line.trim(); // it will skip this violation }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.5
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.
name | description | type | default value | since |
---|---|---|---|---|
allowedDuplicates | The maximum number of occurrences to allow without generating a warning | Integer | 1 | 3.5 |
ignoreStringsRegexp | Regular expression pattern for ignored strings (with quotation marks) | Regular Expression | "^""$" | 4.0 |
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. | subset of tokens TokenTypes | ANNOTATION | 4.4 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.4
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
name | description | type | default value | since |
---|---|---|---|---|
max | allowed nesting depth | Integer | 1 | 5.3 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Restricts nested if-else blocks to a specified depth (default = 1).
name | description | type | default value | since |
---|---|---|---|---|
max | allowed nesting depth | Integer | 1 | 3.2 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
name | description | type | default value | since |
---|---|---|---|---|
max | allowed nesting depth | Integer | 1 | 3.2 |
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>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 5.0
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}
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 5.3
Checks that there is only one statement per line.
Rationale: It's very difficult to read multiple statements on one line.
In the Java programming language, statements are the fundamental unit of execution. All statements except blocks are terminated by a semicolon. Blocks are denoted by open and close curly braces.
OneStatementPerLineCheck checks the following types of statements: variable declaration statements, empty statements, import statements, assignment statements, expression statements, increment statements, object creation statements, 'for loop' statements, 'break' statements, 'continue' statements, 'return' statements.
The following examples will be flagged as a violation:
//Each line causes violation: int var1; int var2; var1 = 1; var2 = 2; int var1 = 1; int var2 = 2; var1++; var2++; Object obj1 = new Object(); Object obj2 = new Object(); import java.io.EOFException; import java.io.BufferedReader; ;; //two empty statements on the same line. //Multi-line statements: int var1 = 1 ; var2 = 2; //violation here int o = 1, p = 2, r = 5; int t; //violation here
An example of how to configure this Check:
<module name="OneStatementPerLine"/>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
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"/>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
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.
Packages provide logical namespace to classes and should be stored in the form of directory levels to provide physical grouping to your classes. These directories are added to the classpath so that your classes are visible to JVM when it runs the code.
name | description | type | default value | since |
---|---|---|---|---|
matchDirectoryStructure | Whether to check for directory and package name match. | Boolean | true | 7.6.1 |
To configure the check:
<module name="PackageDeclaration"/>
Let us consider the class AnnotationLocationCheck which is in the directory /com/puppycrawl/tools/checkstyle/checks/annotations/
package com.puppycrawl.tools.checkstyle.checks; //Violation public class AnnotationLocationCheck extends AbstractCheck { //... }
Example of how the check works when matchDirectoryStructure option is set to false. Let us again consider the AnnotationLocationCheck class located at directory /com/puppycrawl/tools/checkstyle/checks/annotations/ along with the following setup,
<module name="PackageDeclaration"> <property name="matchDirectoryStructure" value="false"/> </module>
package com.puppycrawl.tools.checkstyle.checks; //No Violation public class AnnotationLocationCheck extends AbstractCheck { //... }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.4
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.
Warning: the Check is very controversial if 'validateOnlyOverlapping' option is set to 'false' and not that actual nowadays.
Rationale:
name | description | type | default value | since |
---|---|---|---|---|
checkFields | Whether to check references to fields. | Boolean | true | 3.4 |
checkMethods | Whether to check references to methods. | Boolean | true | 3.4 |
validateOnlyOverlapping | Whether to check only overlapping by variables or arguments. | Boolean | true | 6.17 |
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>
Examples of how the check works if validateOnlyOverlapping option is set to true:
public static class A { private int field1; private int field2; public A(int field1) { // Overlapping by constructor argument. field1 = field1; // violation: Reference to instance variable "field1" needs "this". field2 = 0; } void foo3() { String field1 = "values"; // Overlapping by local variable. field1 = field1; // violation: Reference to instance variable "field1" needs "this". } } public static class B { private int field1; public A(int f) { field1 = f; } String addSuffixToField(String field1) { // Overlapping by method argument. Equal to "return field1 = field1 + "suffix";" return field1 += "suffix"; // violation: Reference to instance variable "field1" needs "this". } }
Please, be aware of the following logic, which is implemented in the check:
1) If you arrange 'this' in your code on your own, the check will not raise violation for variables which use 'this' to reference a class field, for example:
public class C { private int scale; private int x; public void foo(int scale) { scale = this.scale; // no violation if (scale > 0) { scale = -scale; // no violation } x *= scale; } }
2) If method parameter is returned from the method, the check will not raise violation for returned variable/parameter, for example:
public class D { private String prefix; public String modifyPrefix(String prefix) { prefix = "^" + prefix + "$" // no violation (modification of parameter) return prefix; // modified method parameter is returned from the method } }
Examples of how the check works if validateOnlyOverlapping option is set to false:
public static class A { private int field1; private int field2; public A(int field1) { field1 = field1; // violation: Reference to instance variable "field1" needs "this". field2 = 0; // violation: Reference to instance variable "field2" needs "this". String field2; field2 = "0"; // No violation. Local var allowed } void foo3() { String field1 = "values"; field1 = field1; // violation: Reference to instance variable "field1" needs "this". } } public static class B { private int field1; public A(int f) { field1 = f; // violation: Reference to instance variable "field1" needs "this". } String addSuffixToField(String field1) { return field1 += "suffix"; // violation: Reference to instance variable "field1" needs "this". } } // If the variable is locally defined, there won't be a violation provided the variable doesn't overlap. class C { private String s1 = "foo1"; String s2 = "foo2"; C() { s1 = "bar1"; // Violation. Reference to instance variable 's1' needs "this.". String s2; s2 = "bar2"; // No violation. Local var allowed. s2 += s2; // Violation. Overlapping. Reference to instance variable 's2' needs "this.". } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Restricts the number of return statements in methods, constructors and lambda expressions (2 by default). Ignores specified methods (equals() by default).
max property will only check returns in methods and lambdas that return a specific value (Ex: 'return 1;').
maxForVoid property will only check returns in methods, constructors, and lambdas that have no return type (IE 'return;'). It will only count visible return statements. Return statements not normally written, but implied, at the end of the method/constructor definition will not be taken into account. To disallow "return;" in void return type methods, use a value of 0.
Rationale: Too many return points can mean that code is attempting to do too much or may be difficult to understand.
name | description | type | default value | since |
---|---|---|---|---|
max | maximum allowed number of return statements in non-void methods/lambdas | Integer | 2 | 3.2 |
maxForVoid | maximum allowed number of return statements in void methods/constructors/lambdas | Integer | 1 | 6.19 |
format | method names to ignore | Regular Expression | "^equals$" | 3.4 |
tokens | tokens to check | subset of tokens CTOR_DEF, METHOD_DEF, LAMBDA. | CTOR_DEF, METHOD_DEF, LAMBDA. | 3.2 |
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 any return statements per void method:
<module name="ReturnCount"> <property name="maxForVoid" value="0"/> </module>
To configure the check so that it doesn't allow more than 2 return statements per method (ignoring the equals() method) and more than 1 return statements per void method:
<module name="ReturnCount"> <property name="max" value="2"/> <property name="maxForVoid" value="1"/> </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>
To configure the check so that it doesn't allow any return statements in constructors, more than one return statement in all lambda expressions and more than two return statements in methods:
<module name="ReturnCount"> <property name="max" value="0"/> <property name="tokens" value="CTOR_DEF"/> </module> <module name="ReturnCount"> <property name="max" value="1"/> <property name="tokens" value="LAMBDA"/> </module> <module name="ReturnCount"> <property name="max" value="2"/> <property name="tokens" value="METHOD_DEF"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.0
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.0
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
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))
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Checks that an overriding clone() method invokes super.clone(). Does not check native methods, as they have no possible java defined implementation.
Reference: Object.clone().
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 3.2
Checks that an overriding finalize() method invokes super.finalize(). Does not check native methods, as they have no possible java defined implementation.
Reference: Use Finalization Only When You Must.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
name | description | type | default value | since |
---|---|---|---|---|
tokens | tokens to check | subset of tokens EXPR, IDENT, NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG, STRING_LITERAL, LITERAL_NULL, LITERAL_FALSE, LITERAL_TRUE, ASSIGN, BAND_ASSIGN, BOR_ASSIGN, BSR_ASSIGN, BXOR_ASSIGN, DIV_ASSIGN, MINUS_ASSIGN, MOD_ASSIGN, PLUS_ASSIGN, SL_ASSIGN, SR_ASSIGN, STAR_ASSIGN, LAMBDA. | EXPR, IDENT, NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG, STRING_LITERAL, LITERAL_NULL, LITERAL_FALSE, LITERAL_TRUE, ASSIGN, BAND_ASSIGN, BOR_ASSIGN, BSR_ASSIGN, BXOR_ASSIGN, DIV_ASSIGN, MINUS_ASSIGN, MOD_ASSIGN, PLUS_ASSIGN, SL_ASSIGN, SR_ASSIGN, STAR_ASSIGN, LAMBDA. | 3.4 |
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Since Checkstyle 5.8
Checks the distance between declaration of variable and its first usage.
name | description | type | default value | since |
---|---|---|---|---|
allowedDistance | A distance between declaration of variable and its first usage. Values should be greater than 0. | Integer | 3 | 5.8 |
ignoreVariablePattern | pattern for ignoring the distance calculation | Regular Expression | "" | 5.8 |
validateBetweenScopes | Allows to calculate the distance between declaration of variable and its first usage in the different scopes. | Boolean | false | 5.8 |
ignoreFinal | Allows to ignore variables with a 'final' modifier. | Boolean | true | 5.8 |
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="ignoreFinal" value="false"/> </module>
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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.