Since Checkstyle 3.2
Checks that array initialization contains a trailing comma.
int[] a = new int[] { 1, 2, 3, };
By default, 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 trailing 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 trailing comma there's also (more arguable) problem:
{100000000000000000000, // Line cannot be just duplicated to slightly modify entry } {100000000000000000000, 100000000000000000001, // More work needed to duplicate }
name | description | type | default value | since |
---|---|---|---|---|
alwaysDemandTrailingComma | Control whether to always check for a trailing comma, even when an array is inline. | boolean | false |
8.33 |
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
To configure check to always validate trailing comma:
<module name="ArrayTrailingComma"> <property name="alwaysDemandTrailingComma" value="true"/> </module>
Example:
int[] numbers = {1, 2, 3}; // violation boolean[] bools = { true, true, false // violation }; String[][] text = {{},{},}; // OK double[][] decimals = { {0.5, 2.3, 1.1,}, // OK {1.7, 1.9, 0.6}, // violation {0.8, 7.4, 6.5} // violation }; // violation, previous line misses a comma char[] chars = {'a', 'b', 'c' // violation }; String[] letters = { "a", "b", "c"}; // violation int[] a1 = new int[]{ 1, 2 , }; // OK int[] a2 = new int[]{ 1, 2 ,}; // OK
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
Since Checkstyle 8.30
Detects double brace initialization.
Rationale: Double brace initialization (set of Instance Initializers in class body) may look cool, but it is considered as anti-pattern and should be avoided. This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is returned outside and other object(s) hold reference to it. Created anonymous class is not static, it holds an implicit reference to the outer class instance. See this blog post and article for more details. Check ignores any comments and semicolons in class body.
To configure the check:
<module name="AvoidDoubleBraceInitialization"/>
Which results in the following violations:
class MyClass { List<Integer> list1 = new ArrayList<>() { // violation { add(1); } }; List<String> list2 = new ArrayList<>() { // violation ; // comments and semicolons are ignored { add("foo"); } }; }
Check only looks for double brace initialization and it ignores cases where the anonymous class has fields or methods. Though these might create the same memory issues as double brace, the extra class members can produce side effects if changed incorrectly.
class MyClass { List<Object> list = new ArrayList<>() { // OK, not pure double brace pattern private int field; { add(new Object()); } }; }
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
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.
To configure the check:
<module name="AvoidInlineConditionals"/>
Example:
int x = 5; boolean foobar = (x == 5); // OK String text; text = (text == null) ? "" : text; // violation String b; if (a != null && a.length() >= 1) { // OK b = a.substring(1); } else { b = null; } b = (a != null && a.length() >= 1) ? a.substring(1) : null; // 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
Since Checkstyle 8.29
Checks if call to superclass constructor without arguments is present.
Such invocation is redundant because constructor body implicitly
begins with a superclass constructor invocation super();
See
specification for detailed information.
To configure the check:
<module name="AvoidNoArgumentSuperConstructorCall"/>
Example of violations
class MyClass extends SomeOtherClass { MyClass() { super(); // violation } MyClass(int arg) { super(arg); // OK, call with argument have to be explicit } MyClass(long arg) { // OK, call is implicit } }
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
Since Checkstyle 3.2
Checks that classes and records 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 '4.5 Bad Covariant Definition of Equals (Eq)':
Java classes and records 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; } }
Another example:
record Test(String str) { public boolean equals(Test r) { // violation return false; } }
The same record without violations:
record Test(String str) { public boolean equals(Test r) { // no violation return false; } public boolean equals(Object r) { return false; } }
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
Since Checkstyle 3.2
Checks that the parts of a class, record, or interface declaration appear in the order suggested by the Code Conventions for the Java Programming Language.
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 }
To configure the check:
<module name="DeclarationOrder"/>
With default options:
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.
com.puppycrawl.tools.checkstyle.checks.coding
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 |
Control whether to allow default along with
case if they are not last.
|
boolean | false |
7.7 |
To configure the check:
<module name="DefaultComesLast"/>
Example:
switch (i) { case 1: break; case 2: break; default: // OK break; } switch (i) { case 1: break; case 2: break; // OK, no default } switch (i) { case 1: break; default: // violation, 'default' before 'case' break; case 2: break; } switch (i) { case 1: default: // violation, 'default' before 'case' break; case 2: break; }
To configure the check to allow default label to be not last if it is shared with case:
<module name="DefaultComesLast"> <property name="skipIfLastAndSharedWithCase" value="true"/> </module>
Example:
switch (i) { case 1: break; case 2: default: // OK break; case 3: break; } switch (i) { case 1: break; default: // violation case 2: break; } // Switch rules are not subject to fall through, so this is still a violation: switch (i) { case 1 -> x = 9; default -> x = 10; // violation case 2 -> x = 32; }
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
Since Checkstyle 3.1
Detects empty statements (standalone ";"
semicolon).
Empty statements often introduce bugs that are hard to spot
To configure the check:
<module name="EmptyStatement"/>
Example:
public void foo() { int i = 5; if (i > 3); // violation, ";" right after if statement i++; for (i = 0; i < 5; i++); // violation i++; while (i > 10) // OK i++; }
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
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 but following this rule such checks
are not required.
name | description | type | default value | since |
---|---|---|---|---|
ignoreEqualsIgnoreCase |
Control whether to ignore String.equalsIgnoreCase(String) invocations.
|
boolean | false |
5.4 |
To configure the check:
<module name="EqualsAvoidNull"/>
Example:
String nullString = null; nullString.equals("My_Sweet_String"); // violation "My_Sweet_String".equals(nullString); // OK nullString.equalsIgnoreCase("My_Sweet_String"); // violation "My_Sweet_String".equalsIgnoreCase(nullString); // OK
To configure the check to allow ignoreEqualsIgnoreCase:
<module name="EqualsAvoidNull"> <property name="ignoreEqualsIgnoreCase" value="true"/> </module>
Example:
String nullString = null; nullString.equals("My_Sweet_String"); // violation "My_Sweet_String".equals(nullString); // OK nullString.equalsIgnoreCase("My_Sweet_String"); // OK "My_Sweet_String".equalsIgnoreCase(nullString); // OK
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
Since Checkstyle 3.0
Checks that classes that either override equals()
or hashCode()
also overrides the other.
This check 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.
To configure the check:
<module name="EqualsHashCode"/>
Example:
public static class Example1 { public int hashCode() { // code } public boolean equals(String o) { // violation, overloaded implementation of 'equals' // code } } public static class Example2 { public boolean equals(Object o) { // violation, no 'hashCode' // code } public boolean equals(String o) { // code } } public static class Example3 { public int hashCode() { // code } public boolean equals(Object o) { // OK // code } public boolean equals(String o) { // code } } public static class Example4 { public int hashCode() { // code } public boolean equals(java.lang.Object o) { // OK // code } } public static class Example5 { public static int hashCode(int i) { // code } public boolean equals(Object o) { // violation, overloaded implementation of 'hashCode' // code } } public static class Example6 { public int hashCode() { // violation, overloaded implementation of 'equals' // code } public static boolean equals(Object o, Object o2) { // code } }
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
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 there is a minor inefficiency.
name | description | type | default value | since |
---|---|---|---|---|
onlyObjectReferences | control whether only explicit initializations made to null for objects should be checked. | boolean | false |
7.8 |
To configure the check:
<module name="ExplicitInitialization"/>
Example:
public class Test { private int intField1 = 0; // violation private int intField2 = 1; private int intField3; private char charField1 = '\0'; // violation private char charField2 = 'b'; private char charField3; private boolean boolField1 = false; // violation private boolean boolField2 = true; private boolean boolField3; private Obj objField1 = null; // violation private Obj objField2 = new Obj(); private Obj objField3; private int arrField1[] = null; // violation private int arrField2[] = new int[10]; private int arrField3[]; }
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 intField1 = 0; // ignored private int intField2 = 1; private int intField3; private char charField1 = '\0'; // ignored private char charField2 = 'b'; private char charField3; private boolean boolField1 = false; // ignored private boolean boolField2 = true; private boolean boolField3; private Obj objField1 = null; // violation private Obj objField2 = new Obj(); private Obj objField3; private int arrField1[] = null; // violation private int arrField2[] = new int[10]; private int arrField3[]; }
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
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 texts
"fallthru", "fall thru", "fall-thru",
"fallthrough", "fall through", "fall-through"
"fallsthrough", "falls through", "falls-through" (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).
Note: The check assumes that there is no unreachable
code in the case
.
To configure the check:
<module name="FallThrough"/>
Example:
public void foo() throws Exception { int i = 0; while (i >= 0) { switch (i) { case 1: i++; case 2: // violation, previous case contains code but lacks // break, return, throw or continue statement i++; break; case 3: // OK i++; return; case 4: // OK i++; throw new Exception(); case 5: // OK i++; continue; case 6: // OK case 7: // Previous case: OK, case does not contain code // This case: OK, by default the last case might not have statement // that transfer control i++; } } }
Example how to suppress violations by comment:
switch (i) { case 1: i++; // fall through case 2: // OK i++; // fallthru case 3: { // OK i++; } /* fall-thru */ case 4: // OK i++; // Fallthru case 5: // violation, "Fallthru" in case 4 should be "fallthru" i++; // fall through i++; case 6: // violation, the comment must be on the last non-empty line before 'case' i++; /* fall through */case 7: // OK, comment can appear on the same line but before 'case' i++; }
To configure the check to enable check for last case group:
<module name="FallThrough"> <property name="checkLastCaseGroup" value="true"/> </module>
Example:
switch (i) { case 1: break; case 2: // Previous case: OK // This case: violation, last case must have statement that transfer control i++; }
To configure the check with custom relief pattern:
<module name="FallThrough"> <property name="reliefPattern" value="FALL?[ -]?THROUGH"/> </module>
Example:
switch (i) { case 1: i++; // FALL-THROUGH case 2: // OK, "FALL-THROUGH" matches the regular expression "FALL?[ -]?THROUGH" i++; // fall-through case 3: // violation, "fall-through" doesn't match break; }
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
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="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); }
An example of how to configure check on local variables and parameters but do not validate loop variables:
<module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/> <property name="validateEnhancedForLoopVariable" value="false"/> </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
Since Checkstyle 3.0
Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
It is possible to configure the check to ignore all property setter methods.
A method is recognized as a setter if it is in the following form
${returnType} set${Name}(${anyType} ${name}) { ... }
where ${anyType} is any primitive type, class or interface name; ${name} is name of the variable that is being set and ${Name} its capitalized form that appears in the method name. By default it is expected that setter returns void, i.e. ${returnType} is 'void'. For example
void setTime(long time) { ... }
Any other return types will not let method match a setter pattern. However, by setting setterCanReturnItsClass property to true definition of a setter is expanded, so that setter return type can also be a class in which setter is declared. For example
class PageBuilder { PageBuilder setName(String name) { ... } }
Such methods are known as chain-setters and a common when Builder-pattern is used. Property setterCanReturnItsClass has effect only if ignoreSetter is set to true.
name | description | type | default value | since |
---|---|---|---|---|
ignoreFormat | Define the RegExp for names of variables and parameters to ignore. | Pattern | null |
3.2 |
ignoreConstructorParameter | Control whether to ignore constructor parameters. | boolean | false |
3.2 |
ignoreSetter | Allow to ignore the parameter of a property setter method. | boolean | false |
3.2 |
setterCanReturnItsClass | Allow to expand the definition of a setter method to include methods that return the class' instance. | boolean | false |
6.3 |
ignoreAbstractMethods | Control whether to ignore parameters of abstract methods. | boolean | false |
4.0 |
tokens | tokens to check | subset of tokens VARIABLE_DEF , PARAMETER_DEF , PATTERN_VARIABLE_DEF , LAMBDA , RECORD_COMPONENT_DEF . | VARIABLE_DEF , PARAMETER_DEF , PATTERN_VARIABLE_DEF , LAMBDA , RECORD_COMPONENT_DEF . | 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.
com.puppycrawl.tools.checkstyle.checks.coding
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 | Specify exception class names to reject. | String[] | Error, Exception, RuntimeException, Throwable, java.lang.Error,
java.lang.Exception, java.lang.RuntimeException, java.lang.Throwable |
3.2 |
To configure the check:
<module name="IllegalCatch"/>
Example:
try { // some code here } catch (Exception e) { // violation } try { // some code here } catch (ArithmeticException e) { // OK } catch (Exception e) { // violation, catching Exception is illegal and order of catch blocks doesn't matter } try { // some code here } catch (ArithmeticException | Exception e) { // violation, catching Exception is illegal } try { // some code here } catch (ArithmeticException e) { // OK }
To configure the check to override the default list with ArithmeticException and OutOfMemoryError:
<module name="IllegalCatch"> <property name="illegalClassNames" value="ArithmeticException, OutOfMemoryError"/> </module>
Example:
try { // some code here } catch (OutOfMemoryError e) { // violation } try { // some code here } catch (ArithmeticException e) { // violation } try { // some code here } catch (NullPointerException e) { // OK } catch (OutOfMemoryError e) { // violation } try { // some code here } catch (ArithmeticException | Exception e) { // violation } try { // some code here } catch (Exception e) { // OK }
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
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.
There is a limitation that it is currently not possible to specify array classes.
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.
com.puppycrawl.tools.checkstyle.checks.coding
Since Checkstyle 4.0
Checks that specified 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 | Specify throw class names to reject. | String[] | Error, RuntimeException, Throwable, java.lang.Error,
java.lang.RuntimeException, java.lang.Throwable
|
4.0 |
ignoredMethodNames | Specify names of methods to ignore. | String[] | finalize |
5.4 |
ignoreOverriddenMethods |
allow to ignore checking overridden methods (marked with Override
or java.lang.Override annotation).
|
boolean | true |
6.4 |
To configure the check:
<module name="IllegalThrows"/>
Example:
public class Test { public void func1() throws RuntimeException {} // violation public void func2() throws Exception {} // ok public void func3() throws Error {} // violation public void func4() throws Throwable {} // violation public void func5() throws NullPointerException {} // ok @Override public void toString() throws Error {} // ok }
To configure the check rejecting throws NullPointerException from methods:
<module name="IllegalThrows"> <property name="illegalClassNames" value="NullPointerException"/> </module>
Example:
public class Test { public void func1() throws RuntimeException {} // ok public void func2() throws Exception {} // ok public void func3() throws Error {} // ok public void func4() throws Throwable {} // ok public void func5() throws NullPointerException {} // violation @Override public void toString() throws Error {} // ok }
To configure the check ignoring method named "func1()":
<module name="IllegalThrows"> <property name="ignoredMethodNames" value="func1"/> </module>
Example:
public class Test { public void func1() throws RuntimeException {} // ok public void func2() throws Exception {} // ok public void func3() throws Error {} // violation public void func4() throws Throwable {} // violation public void func5() throws NullPointerException {} // ok @Override public void toString() throws Error {} // ok }
To configure the check to warn on overridden methods:
<module name="IllegalThrows"> <property name="ignoreOverriddenMethods" value="false"/> </module>
Example:
public class Test { public void func1() throws RuntimeException {} // violation public void func2() throws Exception {} // ok public void func3() throws Error {} // violation public void func4() throws Throwable {} // violation public void func5() throws NullPointerException {} // ok @Override public void toString() throws Error {} // 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
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 | set of any supported tokens | LABELED_STAT . | 3.2 |
To configure the check:
<module name="IllegalToken"/>
Example:
public void myTest() { outer: // violation for (int i = 0; i < 5; i++) { if (i == 1) { break outer; } } }
To configure the check to report violation on token LITERAL_NATIVE:
<module name="IllegalToken"> <property name="tokens" value="LITERAL_NATIVE"/> </module>
Example:
public native void myTest(); // 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
Since Checkstyle 3.2
Checks specified tokens text for matching an illegal pattern. By default no tokens are specified.
name | description | type | default value | since |
---|---|---|---|---|
format | Define the RegExp for illegal pattern. | Regular Expression | "^$" |
3.2 |
ignoreCase | Control whether to ignore case when matching. | boolean | false |
3.2 |
message | Define the 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 , TEXT_BLOCK_CONTENT . | 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>
Example:
public void myTest() { String test = "a href"; // violation String test2 = "A href"; // OK, case is sensitive }
To configure the check to forbid String literals containing
"a href"
for the ignoreCase mode:
<module name="IllegalTokenText"> <property name="tokens" value="STRING_LITERAL"/> <property name="format" value="a href"/> <property name="ignoreCase" value="true"/> </module>
Example:
public void myTest() { String test = "a href"; // violation String test2 = "A href"; // violation, case is ignored }
To configure the check to forbid string literal text blocks containing
"""
:
<module name="IllegalTokenText"> <property name="tokens" value="TEXT_BLOCK_CONTENT"/> <property name="format" value='"'/> </module>
Example:
public void myTest() { final String quote = """ \""""; // violation }
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>
Example:
public void myTest() { int test1 = 0; // OK int test2 = 0x111; // OK int test3 = 0X111; // OK, case is ignored int test4 = 010; // violation long test5 = 0L; // OK long test6 = 010L; // 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
Since Checkstyle 3.2
Checks that particular classes or interfaces are never used.
Rationale: Helps reduce coupling on concrete classes.
For additional restriction of type usage see also: IllegalInstantiation, IllegalImport
name | description | type | default value | since |
---|---|---|---|---|
validateAbstractClassNames | Control whether to validate abstract class names. | boolean | false |
6.10 |
illegalClassNames | Specify classes that should not be used as types in variable declarations, return values or parameters. | String[] | HashMap, HashSet, LinkedHashMap, LinkedHashSet, TreeMap, TreeSet,
java.util.HashMap, java.util.HashSet, java.util.LinkedHashMap,
java.util.LinkedHashSet, java.util.TreeMap, java.util.TreeSet |
3.2 |
legalAbstractClassNames | Define abstract classes that may be used as types. | String[] | {} |
4.2 |
ignoredMethodNames | Specify methods that should not be checked. | String[] | getEnvironment, getInitialContext |
3.2 |
illegalAbstractClassNameFormat | Specify RegExp for illegal abstract class names. | Pattern | "^(.*[.])?Abstract.*$" |
3.2 |
memberModifiers | Control whether to check only methods and fields with any of the specified modifiers. This property does not affect method calls nor method references. | subset of tokens TokenTypes | {} |
6.3 |
tokens | tokens to check | subset of tokens ANNOTATION_FIELD_DEF , CLASS_DEF , INTERFACE_DEF , METHOD_CALL , METHOD_DEF , METHOD_REF , PARAMETER_DEF , VARIABLE_DEF , PATTERN_VARIABLE_DEF , RECORD_DEF , RECORD_COMPONENT_DEF . | ANNOTATION_FIELD_DEF , CLASS_DEF , INTERFACE_DEF , METHOD_CALL , METHOD_DEF , METHOD_REF , PARAMETER_DEF , VARIABLE_DEF , PATTERN_VARIABLE_DEF , RECORD_DEF , RECORD_COMPONENT_DEF . | 3.2 |
It is possible to set illegal class names via short or
canonical name.
Specifying illegal type invokes analyzing imports and Check puts violations at
corresponding declarations
(of variables, methods or parameters). This helps to avoid ambiguous cases, e.g.:
java.awt.List
was set as illegal class name, then, code like:
import java.util.List; ... List list; //No violation here
will be ok.
In most cases it's justified to put following classes to illegalClassNames:
as methods that are differ from interface methods are rarely used, so in most cases user will benefit from checking for them.
To configure the default check:
<module name="IllegalType"/>
public class Test extends TreeSet { // violation public <T extends java.util.HashSet> void method() { // violation LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); // violation TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // violation Test t; // OK HashMap<String, String> hmap; // violation Queue<Integer> intqueue; // OK java.lang.IllegalArgumentException illegalex; // OK java.util.TreeSet treeset; // violation } }
To configure the Check so that particular tokens are checked:
<module name="IllegalType"> <property name="tokens" value="METHOD_DEF"/> </module>
public class Test extends TreeSet { // OK public <T extends java.util.HashSet> void method() { // violation LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); // OK java.lang.IllegalArgumentException illegalex; // OK java.util.TreeSet treeset; // Ok } public <T extends java.util.HashSet> void typeParam(T t) {} // violation public void fullName(TreeSet a) {} // OK }
To configure the Check so that it ignores function() methods:
<module name="IllegalType"> <property name="ignoredMethodNames" value="function"/> </module>
public class Test { public HashMap<String, String> function() { // OK // code } public HashMap<String, String> function1() { // violation // code } }
To configure the Check so that it validates abstract class names:
<module name="IllegalType"> <property name="validateAbstractClassNames" value="true"/> <property name="illegalAbstractClassNameFormat" value="Gitt"/> </module>
class Test extends Gitter { // violation } class Test1 extends Github { // OK }
To configure the Check so that it verifies only public, protected or static methods and fields:
<module name="IllegalType"> <property name="memberModifiers" value="LITERAL_PUBLIC, LITERAL_PROTECTED, LITERAL_STATIC"/> </module>
public class Test { public HashMap<String, String> function1() { // violation // code } private HashMap<String, String> function2() { // OK // code } protected HashMap<Integer, String> function3() { // violation // code } public static TreeMap<Integer, String> function4() { // violation // code } }
To configure the check so that it verifies usage of types Boolean and Foo:
<module name="IllegalType"> <property name="illegalClassNames" value="Boolean, Foo"/> </module>
public class Test { public Set<Boolean> set; // violation public java.util.List<Map<Boolean, Foo>> list; // violation private void method(List<Foo> list, Boolean value) { // violation SomeType.<Boolean>foo(); // violation final Consumer<Foo> consumer = Foo<Boolean>::foo; // violation } public <T extends Boolean, U extends Serializable> void typeParam(T a) {} // violation public void fullName(java.util.ArrayList<? super Boolean> a) {} // violation public abstract Set<Boolean> shortName(Set<? super Boolean> a); // violation public Set<? extends Foo> typeArgument() { // violation return new TreeSet<Foo<Boolean>>(); } }
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
Since Checkstyle 3.0
Checks for assignments in subexpressions, such as in
String s = Integer.toString(i = 2);
.
Rationale: With the exception of loop idioms, 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 assignments in loops:
String line; while ((line = bufferedReader.readLine()) != null) { // OK // process the line } for (;(line = bufferedReader.readLine()) != null;) { // OK // process the line } do { // process the line } while ((line = bufferedReader.readLine()) != null); // OK
Assignment inside a condition is not a problem here, as the assignment is surrounded by
an extra pair of parentheses. The comparison is != null
and there is no
chance that intention was to write line == reader.readLine()
.
To configure the check:
<module name="InnerAssignment"/>
Example:
class MyClass { void foo() { int a, b; a = b = 5; // violation, assignment to each variable should be in a separate statement a = b += 5; // violation a = 5; // OK b = 5; // OK a = 5; b = 5; // OK double myDouble; double[] doubleArray = new double[] {myDouble = 4.5, 15.5}; // violation String nameOne; List<String> myList = new ArrayList<String>(); myList.add(nameOne = "tom"); // violation for (int k = 0; k < 10; k = k + 2) { // OK // some code } boolean someVal; if (someVal = true) { // violation // some code } while (someVal = false) {} // violation InputStream is = new FileInputStream("textFile.txt"); while ((b = is.read()) != -1) { // OK, this is a common idiom // some code } } boolean testMethod() { boolean val; return val = true; // 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
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.
Constant definition is any variable/field that has 'final' modifier. 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 | Specify non-magic numbers. | double[] | -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 |
ignoreAnnotationElementDefaults | Ignore magic numbers in annotation elements defaults. | boolean | true |
8.23 |
constantWaiverParentToken | Specify tokens 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 } public int hashCode() { return 10; // violation } } @interface anno { int value() default 10; // no 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 } }
To configure the check so that it ignores magic numbers in field declarations:
<module name="MagicNumber"> <property name="ignoreFieldDeclaration" value="false"/> </module>
results in the following violations:
public record MyRecord() { private static int myInt = 7; // ok, field declaration void foo() { int i = myInt + 1; // no violation, 1 is defined as non-magic int j = myInt + 8; // violation } }
To configure the check to check annotation element defaults:
<module name="MagicNumber"> <property name="ignoreAnnotationElementDefaults" value="false"/> </module>
results in following violations:
@interface anno { int value() default 10; // violation int[] value2() default {10}; // violation }
Config example of 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 } }
Config example of ignoreHashCodeMethod option:
<module name="MagicNumber"> <property name="ignoreHashCodeMethod" value="true"/> </module>
result is no violation:
class TestHashCode { public int hashCode() { return 10; // OK } }
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
Since Checkstyle 8.39
Evaluates Xpath query and report violation on all matching AST nodes. This check allows user to implement custom checks using Xpath. If Xpath query is not specified explicitly, then the check does nothing.
It is recommended to define custom message for violation to explain what is not allowed
and what to use instead, default message might be too abstract. To customize a message
you need to add message
element with matchxpath.match as
key
attribute and desired message as value
attribute.
Please read more about Xpath syntax at Xpath Syntax. Information regarding Xpath functions can be found at XSLT/XPath Reference. Note, that @text attribute can used only with token types that are listed in XpathUtil.
name | description | type | default value | since |
---|---|---|---|---|
query | Specify Xpath query. | String | "" |
8.39 |
Checkstyle provides command line tool and GUI application with options to show AST and to ease usage of Xpath queries.
-T option prints AST tree of the checked file.
$ java -jar checkstyle-X.XX-all.jar -T Main.java CLASS_DEF -> CLASS_DEF [1:0] |--MODIFIERS -> MODIFIERS [1:0] | `--LITERAL_PUBLIC -> public [1:0] |--LITERAL_CLASS -> class [1:7] |--IDENT -> Main [1:13] `--OBJBLOCK -> OBJBLOCK [1:18] |--LCURLY -> { [1:18] |--METHOD_DEF -> METHOD_DEF [2:4] | |--MODIFIERS -> MODIFIERS [2:4] | | `--LITERAL_PUBLIC -> public [2:4] | |--TYPE -> TYPE [2:11] | | `--IDENT -> String [2:11] | |--IDENT -> sayHello [2:18] | |--LPAREN -> ( [2:26] | |--PARAMETERS -> PARAMETERS [2:27] | | `--PARAMETER_DEF -> PARAMETER_DEF [2:27] | | |--MODIFIERS -> MODIFIERS [2:27] | | |--TYPE -> TYPE [2:27] | | | `--IDENT -> String [2:27] | | `--IDENT -> name [2:34] | |--RPAREN -> ) [2:38] | `--SLIST -> { [2:40] | |--LITERAL_RETURN -> return [3:8] | | |--EXPR -> EXPR [3:25] | | | `--PLUS -> + [3:25] | | | |--STRING_LITERAL -> "Hello, " [3:15] | | | `--IDENT -> name [3:27] | | `--SEMI -> ; [3:31] | `--RCURLY -> } [4:4] `--RCURLY -> } [5:0]
-b option shows AST nodes that match given Xpath query. This command can be used to validate accuracy of Xpath query against given file.
$ java -jar checkstyle-X.XX-all.jar Main.java -b "//METHOD_DEF[./IDENT[@text='sayHello']]" CLASS_DEF -> CLASS_DEF [1:0] `--OBJBLOCK -> OBJBLOCK [1:18] |--METHOD_DEF -> METHOD_DEF [2:4]
The following example demonstrates validation of methods order, so that public methods should come before the private ones:
<module name="MatchXpath"> <property name="query" value="//METHOD_DEF[.//LITERAL_PRIVATE and following-sibling::METHOD_DEF[.//LITERAL_PUBLIC]]"/> <message key="matchxpath.match" value="Private methods must appear after public methods"/> </module>
Example:
public class Test { public void method1() { } private void method2() { } // violation public void method3() { } private void method4() { } // violation public void method5() { } private void method6() { } // ok }
To violate if there are any parametrized constructors
<module name="MatchXpath"> <property name="query" value="//CTOR_DEF[count(./PARAMETERS/*) > 0]"/> <message key="matchxpath.match" value="Parameterized constructors are not allowed, there should be only default ctor"/> </module>
Example:
public class Test { public Test(Object c) { } // violation public Test(int a, HashMap<String, Integer> b) { } // violation public Test() { } // ok }
To violate if method name is 'test' or 'foo'
<module name="MatchXpath"> <property name="query" value="//METHOD_DEF[./IDENT[@text='test' or @text='foo']]"/> <message key="matchxpath.match" value="Method name should not be 'test' or 'foo'"/> </module>
Example:
public class Test { public void test() {} // violation public void getName() {} // ok public void foo() {} // violation public void sayHello() {} // ok }
To violate if new instance creation was done without var type
<module name="MatchXpath"> <property name="query" value="//VARIABLE_DEF[./ASSIGN/EXPR/LITERAL_NEW and not(./TYPE/IDENT[@text='var'])]"/> <message key="matchxpath.match" value="New instances should be created via 'var' keyword to avoid duplication of type reference in statement"/> </module>
Example:
public class Test { public void foo() { SomeObject a = new SomeObject(); // violation var b = new SomeObject(); // OK } }
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
Since Checkstyle 3.4
Checks that classes (except abstract ones) define a constructor and don't rely on the default one.
To configure the check:
<module name="MissingCtor"/>
Example:
class ExampleOk { // OK private int a; ExampleOk(int a) { this.a = a; } } class ExampleDefaultCtor { // OK private String s; ExampleDefaultCtor() { s = "foobar"; } } class InvalidExample { // violation, class must have a constructor. public void test() {} } abstract class AbstractExample { // OK public abstract void test() {} }
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
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. Note that the compiler requires switch expressions to be exhaustive, so this check does not enforce default branches on such expressions.
To configure the check:
<module name="MissingSwitchDefault"/>
Example of violation:
switch (i) { // violation case 1: break; case 2: break; }
Example of correct code:
switch (i) { case 1: break; case 2: break; default: // OK break; }
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
Since Checkstyle 3.5
Checks 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 | Control 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.
com.puppycrawl.tools.checkstyle.checks.coding
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 | Specify the maximum number of occurrences to allow without generating a warning. | int | 1 |
3.5 |
ignoreStringsRegexp | Specify RegExp for ignored strings (with quotation marks). | Pattern | "^""$" |
4.0 |
ignoreOccurrenceContext | Specify 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.
com.puppycrawl.tools.checkstyle.checks.coding
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.
To configure the check:
<module name="MultipleVariableDeclarations"/>
Example:
public class Test { public void myTest() { int mid; int high; // ... int lower, higher; // violation // ... int value, index; // violation // ... int place = mid, number = high; // 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
Since Checkstyle 5.3
Restricts nested for
blocks to a specified depth.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify maximum allowed nesting depth. | int | 1 |
5.3 |
To configure the check:
<module name="NestedForDepth"/>
Example:
for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { // violation, max allowed nested loop number is 1 } } } for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { // ok } }
To configure the check to allow nesting depth 2:
<module name="NestedForDepth"> <property name="max" value="2"/> </module>
Example:
for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { for(int l=0; l<k; l++) { // violation, max allowed nested loop number is 2 } } } } for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { // ok } } }
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
Since Checkstyle 3.2
Restricts nested if-else blocks to a specified depth.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify maximum allowed nesting depth. | int | 1 |
3.2 |
To configure the check:
<module name="NestedIfDepth"/>
Valid code example:
if (true) { if (true) {} // OK else {} }
Invalid code example:
if (true) { if (true) { if (true) { // violation, nested if-else depth is 2 (max allowed is 1) } } }
To configure the check to allow nesting depth 3:
<module name="NestedIfDepth"> <property name="max" value="3"/> </module>
Valid code example:
if (true) { if (true) { if (true) { if (true) {} // OK else {} } } }
Invalid code example:
if (true) { if (true) { if (true) { if (true) { if (true) { // violation, nested if-else depth is 4 (max allowed is 3) if (true) {} // violation, nested if-else depth is 5 (max allowed is 3) else {} } } } } }
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
Since Checkstyle 3.2
Restricts nested try-catch-finally blocks to a specified depth.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify maximum allowed nesting depth. | int | 1 |
3.2 |
To configure the check:
<module name="NestedTryDepth"/>
case 1: Example of code with violation:
try { try { try { // violation, current depth is 2, default max allowed depth is 1 } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { }
case 1: Example of compliant code:
try { try { // OK, current depth is 1, default max allowed depth is also 1 } catch (Exception e) { } } catch (Exception e) { }
case 2: Example of code for handling unique and general exceptions
try { try { // OK, current depth is 1, default max allowed depth is also 1 // any more nesting could cause code violation! throw ArithmeticException(); } catch (ArithmeticException e) { // catches arithmetic exceptions } catch (NumberFormatException e) { // catches number-format exceptions } catch (Exception e) { // catches general exceptions other than stated above } } catch ( ArithmeticException | NumberFormatException | ArrayIndexOutOfBoundsException e) { // catches any of the 3 exception } catch (Exception e) { // catches general exception } finally { // do something when try-catch block finished execution }
To configure the check to allow nesting depth 3:
<module name="NestedTryDepth"> <property name="max" value="3"/> </module>
Example of code with violation:
try { try { try { try { try { // violation, current depth is 4, max allowed depth is 3 } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { }
Example of compliant code:
try { try { try { try { // OK, current depth is 3, max allowed depth is also 3 } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { }
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
Since Checkstyle 8.28
Checks that array initialization do not contain a trailing comma. Rationale: JLS allows trailing commas in arrays and enumerations, but does not allow them in other locations. To unify the coding style, the use of trailing commas should be prohibited.
int[] foo = new int[] { 1, 2 };
The check demands that there should not be any comma after the last element of an array.
String[] foo = new String[] { "FOO", "BAR", //violation }
To configure the check:
<module name="NoArrayTrailingComma"/>
Which results in the following violations:
String[] foo1 = { "FOO", // OK "BAR", // violation }; String[] foo2 = { "FOO", "BAR", }; // violation String[] foo3 = { "FOO", // OK "BAR" // OK }; String[] foo4 = { "FOO", "BAR" }; // OK
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
Since Checkstyle 5.0
Checks that the clone method is not overridden from the Object class.
This check is almost exactly the same as the NoFinalizerCheck
.
See Object.clone()
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.
Below are some of the rules/reasons why the clone method should be avoided.
Two alternatives to the clone method, in some cases, is a copy constructor or a static factory method to return copies of an object. Both of these approaches are simpler and do not conflict with final fields. They do not force the calling client to handle a CloneNotSupportedException. They also are typed therefore no casting is necessary. Finally, they are more flexible since they can take interface types rather than concrete classes.
Sometimes a copy constructor or static factory is not an acceptable alternative to the clone method. The example below highlights the limitation of a copy constructor (or static factory). Assume Square is a subclass for Shape.
Shape s1 = new Square(); System.out.println(s1 instanceof Square); //true
...assume at this point the code knows nothing of s1 being a Square that's the beauty of polymorphism but the code wants to copy the Square which is declared as a Shape, its super type...
Shape s2 = new Shape(s1); //using the copy constructor System.out.println(s2 instanceof Square); //false
The working solution (without knowing about all subclasses and doing many casts) is to do the following (assuming correct clone implementation).
Shape s2 = s1.clone(); System.out.println(s2 instanceof Square); //true
Just keep in mind if this type of polymorphic cloning is required then a properly implemented clone method may be the best choice.
Much of this information was taken from Effective Java: Programming Language Guide First Edition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.
To configure the check:
<module name="NoClone"/>
Example:
public class Foo { public Object clone() {return null;} // violation, overrides the clone method public Foo clone() {return null;} // violation, overrides the clone method public static Object clone(Object o) {return null;} // OK public static Foo clone(Foo o) {return null;} // OK }
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
Since Checkstyle 8.29
Checks that enum definition does not contain a trailing comma. Rationale: JLS allows trailing commas in arrays and enumerations, but does not allow them in other locations. To unify the coding style, the use of trailing commas should be prohibited.
enum Foo1 { FOO, BAR; }
The check demands that there should not be any comma after last constant in enum definition.
enum Foo1 { FOO, BAR, //violation }
To configure the check:
<module name="NoEnumTrailingComma"/>
Which results in the following violations:
enum Foo1 { FOO, BAR; //OK } enum Foo2 { FOO, BAR //OK } enum Foo3 { FOO, BAR, //violation } enum Foo4 { FOO, BAR, // violation ; } enum Foo5 { FOO, BAR,; // violation } enum Foo6 { FOO, BAR,; } // violation enum Foo7 { FOO, BAR, } // violation enum Foo8 { FOO, BAR // OK ; } enum Foo9 { FOO, BAR; } // OK enum Foo10 { FOO, BAR } // OK
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
Since Checkstyle 5.0
Checks that there is no method finalize
with zero parameters.
Rationale: Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. For more information for the finalize method and its issues, see Effective Java: Programming Language Guide Third Edition by Joshua Bloch, §8.
To configure the check:
<module name="NoFinalizer"/>
Example:
public class Test { protected void finalize() throws Throwable { // violation try { System.out.println("overriding finalize()"); } catch (Throwable t) { throw t; } finally { super.finalize(); } } }
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
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, resources statements (optional).
name | description | type | default value | since |
---|---|---|---|---|
treatTryResourcesAsStatement | Enable resources processing. | boolean | false |
8.23 |
To configure the check:
<module name="OneStatementPerLine"/>
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 the check to treat resources in a try statement as statements to require them on their own line:
<module name="OneStatementPerLine"> <property name="treatTryResourcesAsStatement" value="true"/> </module>
Note: resource declarations can contain variable definitions and variable references (from java9). When property "treatTryResourcesAsStatement" is enabled, this check is only applied to variable definitions. If there are one or more variable references and one variable definition on the same line in resources declaration, there is no violation. The following examples will illustrate difference:
OutputStream s1 = new PipedOutputStream(); OutputStream s2 = new PipedOutputStream(); // only one statement(variable definition) with two variable references try (s1; s2; OutputStream s3 = new PipedOutputStream();) // OK {} // two statements with variable definitions try (Reader r = new PipedReader(); s2; Reader s3 = new PipedReader() // 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
Since Checkstyle 5.8
Checks that overloaded methods are grouped together. Overloaded methods have the same name but different signatures where the signature can differ by the number of input parameters or type of input parameters or both.
To configure the check:
<module name="OverloadMethodsDeclarationOrder"/>
Example of correct grouping of overloaded methods:
public void foo(int i) {} public void foo(String s) {} public void foo(String s, int i) {} public void foo(int i, String s) {} public void notFoo() {}
Example of incorrect grouping of overloaded methods:
public void foo(int i) {} // OK public void foo(String s) {} // OK public void notFoo() {} // violation. Have to be after foo(String s, int i) public void foo(int i, String s) {} public void foo(String s, int i) {}
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
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 | Control 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.
com.puppycrawl.tools.checkstyle.checks.coding
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.
To configure the check:
<module name="ParameterAssignment"/>
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
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:
Limitations: Nothing is currently done about static variables or catch-blocks. Static methods invoked on a class name seem to be OK; both the class name and the method name have a DOT parent. Non-static methods invoked on either this or a variable name seem to be OK, likewise.
name | description | type | default value | since |
---|---|---|---|---|
checkFields | Control whether to check references to fields. | boolean | true |
3.4 |
checkMethods | Control whether to check references to methods. | boolean | true |
3.4 |
validateOnlyOverlapping | Control 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 field; public A(int f) { field = f; } String addSuffixToField(String field) { // Overlapping by method argument. Equal to "return field = field + "suffix";" return field += "suffix"; // violation: Reference to instance variable "field" needs "this". } } public static record C(int x) { void getTwoX(int x) { // Overlapping by method argument. return x += x; // violation: Reference to instance variable "x" 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 field; public A(int f) { field = f; // violation: Reference to instance variable "field" needs "this". } String addSuffixToField(String field) { return field += "suffix"; // violation: Reference to instance variable "field" 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.". } } public static record D(int x) { public D { x = x; // violation: Reference to instance variable "x" needs "this". } }
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
Since Checkstyle 3.2
Restricts the number of return statements in methods, constructors and lambda expressions.
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 | Specify maximum allowed number of return statements in non-void methods/lambdas. | int | 2 |
3.2 |
maxForVoid | Specify maximum allowed number of return statements in void methods/constructors/lambdas. | int | 1 |
6.19 |
format | Specify method names to ignore. | Pattern | "^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.
com.puppycrawl.tools.checkstyle.checks.coding
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.
To configure the check:
<module name="SimplifyBooleanExpression"/>
Example:
public class Test { public void bar() { boolean a, b; Foo c, d, e; if (!false) {}; // violation, can be simplified to true if (a == true) {}; // violation, can be simplified to a if (a == b) {}; // OK if (a == false) {}; // violation, can be simplified to !a if (!(a != true)) {}; // violation, can be simplified to a e = (a || b) ? c : d; // OK e = (a || false) ? c : d; // violation, can be simplified to a e = (a && b) ? c : d; // OK } }
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
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.
To configure the check:
<module name="SimplifyBooleanReturn"/>
Example:
public class Test { private boolean cond; private Foo a; private Foo b; public boolean check1() { if (cond) { // violation, can be simplified return true; } else { return false; } } // Ok, simplified version of check1() public boolean check2() { return cond; } // violations, can be simplified public boolean check3() { if (cond == true) { // can be simplified to "if (cond)" return false; } else { return true; // can be simplified to "return !cond" } } // Ok, can be simplified but doesn't return a Boolean public Foo choose1() { if (cond) { return a; } else { return b; } } // Ok, simplified version of choose1() public Foo choose2() { return cond ? a: b; } }
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
Since Checkstyle 3.2
Checks that string literals are not used with ==
or
!=
.
Since ==
will compare the object references,
not the actual value of the strings,
String.equals()
should be used.
More information can be found
in this article.
Rationale: Novice Java programmers often use code like:
if (x == "something")
when they mean
if ("something".equals(x))
To configure the check:
<module name="StringLiteralEquality"/>
Examples of violations:
String status = "pending"; if (status == "done") {} // violation while (status != "done") {} // violation boolean flag = (status == "done"); // violation boolean flag = (status.equals("done")); // OK String name = "X"; if (name == getName()) {} // OK, limitation that check cannot tell runtime type returned from method call
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
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().
To configure the check:
<module name="SuperClone"/>
Example:
class A { public Object clone() { // OK return super.clone(); } } class B { private int b; public B clone() { // violation, does not call super.clone() B other = new B(); other.b = this.b; return other; } } class C { public C clone() { // OK return (C) super.clone(); } }
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
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.
References: How to Handle Java Finalization's Memory-Retention Issues; 10 points on finalize method in Java.
To configure the check:
<module name="SuperFinalize"/>
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
Since Checkstyle 3.4
Checks if unnecessary parentheses are used in a statement or expression. The check will flag the following with warnings:
return (x); // parens around identifier return (x + 1); // parens around return value int x = (y / 2 + 1); // parens around assignment rhs for (int i = (0); i < 10; i++) { // parens around literal t -= (z + 1); // parens around assignment rhs
The check is not "type aware", that is to say, it can't tell if parentheses are unnecessary based on the types in an expression. It also doesn't know about operator precedence and associativity; therefore it won't catch something like
int x = (a + b) + c;
In the above case, given that a, b, and c are all
int
variables, the parentheses around a + b
are not needed.
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 , TEXT_BLOCK_LITERAL_BEGIN . | 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 , TEXT_BLOCK_LITERAL_BEGIN . | 3.4 |
To configure the check:
<module name="UnnecessaryParentheses"/>
Which results in the following violations:
public int square(int a, int b){ int square = (a * b); //violation return (square); //violation } int sumOfSquares = 0; for(int i=(0); i<10; i++){ //violation int x = (i + 1); //violation sumOfSquares += (square(x * x)); //violation } double num = (10.0); //violation List<String> list = Arrays.asList("a1", "b1", "c1"); myList.stream() .filter((s) -> s.startsWith("c")) //violation .forEach(System.out::println);
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
Since Checkstyle 8.31
Checks if unnecessary semicolon is used after type declaration.
This check is not applicable to nested type declarations, UnnecessarySemicolonAfterTypeMemberDeclaration is responsible for it.
name | description | type | default value | since |
---|---|---|---|---|
tokens | tokens to check | subset of tokens CLASS_DEF , INTERFACE_DEF , ENUM_DEF , ANNOTATION_DEF , RECORD_DEF . | CLASS_DEF , INTERFACE_DEF , ENUM_DEF , ANNOTATION_DEF , RECORD_DEF . | 8.31 |
To configure the check:
<module name="UnnecessarySemicolonAfterOuterTypeDeclaration"/>
Example:
class A { class Nested { }; // OK, nested type declarations are ignored }; // violation interface B { }; // violation enum C { }; // violation {@literal @}interface D { }; // violation
To configure the check to detect unnecessary semicolon only after top level class definitions:
<module name="UnnecessarySemicolonAfterOuterTypeDeclaration"> <property name="tokens" value="CLASS_DEF"/> </module>
Example:
class A { }; // violation interface B { }; // OK enum C { }; // OK {@literal @}interface D { }; // OK
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
Since Checkstyle 8.24
Checks if unnecessary semicolon is used after type member declaration.
This check is not applicable to empty statements (unnecessary semicolons inside methods or init blocks), EmptyStatement is responsible for it.
name | description | type | default value | since |
---|---|---|---|---|
tokens | tokens to check | subset of tokens CLASS_DEF , INTERFACE_DEF , ENUM_DEF , ANNOTATION_DEF , VARIABLE_DEF , ANNOTATION_FIELD_DEF , STATIC_INIT , INSTANCE_INIT , CTOR_DEF , METHOD_DEF , ENUM_CONSTANT_DEF , COMPACT_CTOR_DEF , RECORD_DEF . | CLASS_DEF , INTERFACE_DEF , ENUM_DEF , ANNOTATION_DEF , VARIABLE_DEF , ANNOTATION_FIELD_DEF , STATIC_INIT , INSTANCE_INIT , CTOR_DEF , METHOD_DEF , ENUM_CONSTANT_DEF , COMPACT_CTOR_DEF , RECORD_DEF . | 8.24 |
To configure the check:
<module name="UnnecessarySemicolonAfterTypeMemberDeclaration"/>
Results in following:
class A { ; // violation, standalone semicolon {}; // violation, extra semicolon after init block static {}; // violation, extra semicolon after static init block A(){}; // violation, extra semicolon after constructor definition void method() {}; // violation, extra semicolon after method definition int field = 10;; // violation, extra semicolon after field declaration { ; // no violation, it is empty statement inside init block } static { ; // no violation, it is empty statement inside static init block } void anotherMethod() { ; // no violation, it is empty statement if(true); // no violation, it is empty statement } }
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
Since Checkstyle 8.22
Checks if unnecessary semicolon is in enum definitions. Semicolon is not needed if enum body contains only enum constants.
To configure the check:
<module name="UnnecessarySemicolonInEnumeration"/>
Example of violations
enum One { A,B; // violation } enum Two { A,B,; // violation } enum Three { A,B(); // violation } enum Four { A,B{}; // violation } enum Five { A, B ; // violation }
Example of good cases
enum Normal { A, B, ; // required ";", no violation Normal(){} } enum NoSemicolon { A, B // only enum constants, no semicolon required }
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
Since Checkstyle 8.22
Checks if unnecessary semicolon is used in last resource declaration.
name | description | type | default value | since |
---|---|---|---|---|
allowWhenNoBraceAfterSemicolon | Allow unnecessary semicolon if closing paren is not on the same line. | boolean | true |
8.22 |
To configure the check:
<module name="UnnecessarySemicolonInTryWithResources"/>
Example of violations
class A { void method() throws IOException { try(Reader r1 = new PipedReader();){} // violation try(Reader r4 = new PipedReader();Reader r5 = new PipedReader() ;){} // violation try(Reader r6 = new PipedReader(); Reader r7 = new PipedReader(); ){} } }
To configure the check to detect unnecessary semicolon if closing paren is not on same line
<module name="UnnecessarySemicolonInTryWithResources"> <property name="allowWhenNoBraceAfterSemicolon" value="false"/> </module>
Example of exclusion
class A { void method() throws IOException { try(Reader r1 = new PipedReader();){} // violation try(Reader r6 = new PipedReader(); Reader r7 = new PipedReader(); // 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
Since Checkstyle 5.8
Checks the distance between declaration of variable and its first usage. Note : Variable declaration/initialization statements are not counted while calculating length.
name | description | type | default value | since |
---|---|---|---|---|
allowedDistance | Specify distance between declaration of variable and its first usage. Values should be greater than 0. | int | 3 |
5.8 |
ignoreVariablePattern | Define RegExp to ignore distance calculation for variables listed in this pattern. | Pattern | "" |
5.8 |
validateBetweenScopes | Allow to calculate the distance between declaration of variable and its first usage in the different scopes. | boolean | false |
5.8 |
ignoreFinal | Allow to ignore variables with a 'final' modifier. | boolean | true |
5.8 |
To configure the check with default config:
<module name="VariableDeclarationUsageDistance"/>
Example:
public class Test { public void foo1() { int num; // violation, distance = 4 final int PI; // OK, final variables not checked System.out.println("Statement 1"); System.out.println("Statement 2"); System.out.println("Statement 3"); num = 1; PI = 3.14; } public void foo2() { int a; // OK, used in different scope int b; // OK, used in different scope int count = 0; // OK, used in different scope { System.out.println("Inside inner scope"); a = 1; b = 2; count++; } } }
Check can detect a block of initialization methods. If a variable is used in such a block and there are no other statements after variable declaration, 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.
To configure the check to set allowed distance:
<module name="VariableDeclarationUsageDistance"> <property name="allowedDistance" value="4"/> </module>
Example:
public class Test { public void foo1() { int num; // OK, distance = 4 final int PI; // OK, final variables not checked System.out.println("Statement 1"); System.out.println("Statement 2"); System.out.println("Statement 3"); num = 1; PI = 3.14; } public void foo2() { int a; // OK, used in different scope int b; // OK, used in different scope int count = 0; // OK, used in different scope { System.out.println("Inside inner scope"); a = 1; b = 2; count++; } } }
To configure the check to ignore certain variables:
<module name="VariableDeclarationUsageDistance"> <property name="ignoreVariablePattern" value="^num$"/> </module>
This configuration ignores variables named "num".
Example:
public class Test { public void foo1() { int num; // OK, variable ignored final int PI; // OK, final variables not checked System.out.println("Statement 1"); System.out.println("Statement 2"); System.out.println("Statement 3"); num = 1; PI = 3.14; } public void foo2() { int a; // OK, used in different scope int b; // OK, used in different scope int count = 0; // OK, used in different scope { System.out.println("Inside inner scope"); a = 1; b = 2; count++; } } }
To configure the check to force validation between scopes:
<module name="VariableDeclarationUsageDistance"> <property name="validateBetweenScopes" value="true"/> </module>
Example:
public class Test { public void foo1() { int num; // violation, distance = 4 final int PI; // OK, final variables not checked System.out.println("Statement 1"); System.out.println("Statement 2"); System.out.println("Statement 3"); num = 1; PI = 3.14; } public void foo2() { int a; // OK, distance = 2 int b; // OK, distance = 3 int count = 0; // violation, distance = 4 { System.out.println("Inside inner scope"); a = 1; b = 2; count++; } } }
To configure the check to check final variables:
<module name="VariableDeclarationUsageDistance"> <property name="ignoreFinal" value="false"/> </module>
Example:
public class Test { public void foo1() { int num; // violation, distance = 4 final int PI; // violation, distance = 5 System.out.println("Statement 1"); System.out.println("Statement 2"); System.out.println("Statement 3"); num = 1; PI = 3.14; } public void foo2() { int a; // OK, used in different scope int b; // OK, used in different scope int count = 0; // OK, used in different scope { System.out.println("Inside inner scope"); a = 1; b = 2; count++; } } }
ATTENTION! (Unsupported 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 than the default (=1), 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 the 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.
com.puppycrawl.tools.checkstyle.checks.coding