Checkstyle Rules Explained Briefly | Generated by AI
Below, I’ll explain each rule from the Checkstyle configuration file you provided, along with a small example of code that would violate the rule and a brief description of why it’s flagged. The rules are grouped by category as in your description, and I’ll keep the explanations concise while ensuring clarity. Each example assumes the rule is active with default settings unless specified otherwise. For rules with configurable properties (e.g., max line length), I’ll use typical defaults (e.g., 80 characters for LineLength) unless otherwise noted.
Root Module: <module name="Checker">
The Checker
module is the top-level orchestrator for all checks and filters. It applies to .java
, .properties
, and .xml
files and sets the severity to error
.
Properties
- severity=”error”: All violations are treated as errors.
- fileExtensions=”java, properties, xml”: Checks apply to these file types.
File Filters
These filter which files are checked.
- BeforeExecutionExclusionFileFilter
- Purpose: Excludes files matching a regex (e.g.,
module-info.java
). - Example Violation:
// module-info.java module com.example { requires java.base; }
- Why Flagged: This file matches the regex
module\-info\.java$
and is excluded from checks. No violation occurs for this file, but other files are still checked.
- Purpose: Excludes files matching a regex (e.g.,
- SuppressionFilter
- Purpose: Suppresses checks based on rules in a file (e.g.,
checkstyle-suppressions.xml
). - Example Violation: If
checkstyle-suppressions.xml
suppressesLineLength
for a specific file, a long line in that file won’t be flagged. Without suppression:public class MyClass { // This line is very long and exceeds the default maximum length of 80 characters, causing an error. }
- Why Flagged: Without a suppression rule, the long line violates
LineLength
.
- Purpose: Suppresses checks based on rules in a file (e.g.,
- SuppressWarningsFilter
- Purpose: Allows suppression of checks using
@SuppressWarnings("checkstyle:<check-name>")
. - Example Violation:
public class MyClass { int my_field; // Violates MemberName (not camelCase) }
@SuppressWarnings("checkstyle:MemberName") public class MyClass { int my_field; // No violation due to suppression }
- Why Flagged: Without suppression,
my_field
violatesMemberName
(expects camelCase, e.g.,myField
).
- Purpose: Allows suppression of checks using
Miscellaneous Checks
These apply to general file properties.
- JavadocPackage
- Purpose: Ensures each package has a
package-info.java
with Javadoc. - Example Violation:
// com/example/package-info.java (missing or no Javadoc) package com.example;
- Why Flagged: Missing Javadoc comment (e.g.,
/** Package description */
).
- Purpose: Ensures each package has a
- NewlineAtEndOfFile
- Purpose: Ensures files end with a newline.
- Example Violation:
public class MyClass {} // No newline at end
- Why Flagged: File ends without a newline character.
- Translation
- Purpose: Verifies
.properties
files for internationalization have consistent keys. - Example Violation:
# messages.properties key1=Hello key2=World
# messages_fr.properties key1=Bonjour # Missing key2
- Why Flagged:
messages_fr.properties
lackskey2
, which exists inmessages.properties
.
- Purpose: Verifies
Size Checks
These enforce limits on file and line lengths.
- FileLength
- Purpose: Limits total lines in a file (default typically 2000 lines).
- Example Violation: A 2001-line Java file.
- Why Flagged: Exceeds default line limit.
- LineLength
- Purpose: Ensures lines don’t exceed a max length (default 80 characters).
- Example Violation:
public class MyClass { public void myMethodWithVeryLongNameToExceedEightyCharactersInALine() {} }
- Why Flagged: Line exceeds 80 characters.
Whitespace Checks
These enforce consistent whitespace usage.
- FileTabCharacter
- Purpose: Prohibits tab characters (
\t
) in source files. - Example Violation:
public class MyClass { → int x; // Tab character used for indentation }
- Why Flagged: Tabs are used instead of spaces.
- Purpose: Prohibits tab characters (
- RegexpSingleline
- Purpose: Detects trailing whitespace (lines ending with
\s+$
). - Example Violation:
public class MyClass { // Trailing spaces }
- Why Flagged: Line ends with whitespace.
- Purpose: Detects trailing whitespace (lines ending with
Header Check (Commented Out)
- Header
- Purpose: Enforces a specific file header (e.g., copyright notice) from
checkstyle.header.file
. - Example Violation (if enabled):
// Missing header public class MyClass {}
- Why Flagged: Lacks required header (e.g.,
// Copyright 2025 Example Inc.
).
- Purpose: Enforces a specific file header (e.g., copyright notice) from
Submodule: <module name="TreeWalker">
The TreeWalker
processes the Java AST for detailed checks.
Javadoc Checks
These enforce proper Javadoc comments.
- InvalidJavadocPosition
- Purpose: Ensures Javadoc comments are before classes/methods, not elsewhere.
- Example Violation:
public class MyClass { /** This is misplaced Javadoc */ int x; }
- Why Flagged: Javadoc is not before a class/method declaration.
- JavadocMethod
- Purpose: Checks methods for proper Javadoc (parameters, return, exceptions).
- Example Violation:
public int add(int a, int b) { return a + b; }
- Why Flagged: Missing Javadoc for public method.
- JavadocType
- Purpose: Ensures classes/interfaces/enums have Javadoc.
- Example Violation:
public class MyClass {}
- Why Flagged: Missing Javadoc for class.
- JavadocVariable
- Purpose: Requires Javadoc for public/protected fields.
- Example Violation:
public class MyClass { public int x; }
- Why Flagged: Missing Javadoc for public field.
- JavadocStyle
- Purpose: Enforces Javadoc style (e.g., valid HTML, no malformed comments).
- Example Violation:
/** Missing period at end */ public class MyClass {}
- Why Flagged: Javadoc lacks a period at the end.
- MissingJavadocMethod
- Purpose: Flags methods missing Javadoc.
- Example Violation:
public void myMethod() {}
- Why Flagged: Public method lacks Javadoc.
Naming Conventions
These enforce naming patterns.
- ConstantName
- Purpose: Constants (
static final
) must beUPPER_CASE
. - Example Violation:
public class MyClass { static final int myConstant = 42; }
- Why Flagged:
myConstant
should beMY_CONSTANT
.
- Purpose: Constants (
- LocalFinalVariableName
- Purpose: Local
final
variables must becamelCase
. - Example Violation:
public void myMethod() { final int MY_VAR = 1; }
- Why Flagged:
MY_VAR
should bemyVar
.
- Purpose: Local
- LocalVariableName
- Purpose: Local variables must be
camelCase
. - Example Violation:
public void myMethod() { int MY_VAR = 1; }
- Why Flagged:
MY_VAR
should bemyVar
.
- Purpose: Local variables must be
- MemberName
- Purpose: Instance fields must be
camelCase
. - Example Violation:
public class MyClass { int my_field; }
- Why Flagged:
my_field
should bemyField
.
- Purpose: Instance fields must be
- MethodName
- Purpose: Methods must be
camelCase
. - Example Violation:
public void MyMethod() {}
- Why Flagged:
MyMethod
should bemyMethod
.
- Purpose: Methods must be
- PackageName
- Purpose: Packages must be lowercase with dots (e.g.,
com.example
). - Example Violation:
package com.Example;
- Why Flagged:
Example
should beexample
.
- Purpose: Packages must be lowercase with dots (e.g.,
- ParameterName
- Purpose: Method parameters must be
camelCase
. - Example Violation:
public void myMethod(int MY_PARAM) {}
- Why Flagged:
MY_PARAM
should bemyParam
.
- Purpose: Method parameters must be
- StaticVariableName
- Purpose: Static (non-final) fields must follow a naming pattern.
- Example Violation:
public class MyClass { static int MY_FIELD; }
- Why Flagged:
MY_FIELD
should bemyField
(assuming camelCase).
- TypeName
- Purpose: Class/interface/enum names must be
UpperCamelCase
. - Example Violation:
public class myClass {}
- Why Flagged:
myClass
should beMyClass
.
- Purpose: Class/interface/enum names must be
Import Checks
These regulate import statements.
- AvoidStarImport
- Purpose: Prohibits wildcard imports (e.g.,
import java.util.*
). - Example Violation:
import java.util.*;
- Why Flagged: Uses
*
instead of specific imports (e.g.,import java.util.List
).
- Purpose: Prohibits wildcard imports (e.g.,
- IllegalImport
- Purpose: Blocks imports from restricted packages (e.g.,
sun.*
). - Example Violation:
import sun.misc.Unsafe;
- Why Flagged:
sun.misc.Unsafe
is in a restricted package.
- Purpose: Blocks imports from restricted packages (e.g.,
- RedundantImport
- Purpose: Flags duplicate or unnecessary imports.
- Example Violation:
import java.util.List; import java.util.List;
- Why Flagged: Duplicate import of
List
.
- UnusedImports
- Purpose: Detects unused imports.
- Example Violation:
import java.util.List; public class MyClass {}
- Why Flagged:
List
is imported but not used.
Size Checks
These limit method and parameter counts.
- MethodLength
- Purpose: Limits method length (default typically 150 lines).
- Example Violation: A method with 151 lines.
- Why Flagged: Exceeds default line limit.
- ParameterNumber
- Purpose: Limits method parameters (default typically 7).
- Example Violation:
public void myMethod(int a, int b, int c, int d, int e, int f, int g, int h) {}
- Why Flagged: 8 parameters exceed the default limit of 7.
Whitespace Checks
These enforce consistent whitespace in code.
- EmptyForIteratorPad
- Purpose: Checks padding in empty
for
loop iterators. - Example Violation:
for (int i = 0; ; i++) {}
- Why Flagged: Empty iterator section should have space (e.g.,
for (int i = 0; ; i++)
).
- Purpose: Checks padding in empty
- GenericWhitespace
- Purpose: Ensures spacing around generic types (e.g.,
List<String>
). - Example Violation:
List<String>list;
- Why Flagged: No space between
>
andlist
.
- Purpose: Ensures spacing around generic types (e.g.,
- MethodParamPad
- Purpose: Checks spacing before method parameter lists.
- Example Violation:
public void myMethod (int x) {}
- Why Flagged: Space before
(int x)
is incorrect.
- NoWhitespaceAfter
- Purpose: Prohibits whitespace after certain tokens (e.g.,
++
). - Example Violation:
int x = y ++ ;
- Why Flagged: Space after
++
.
- Purpose: Prohibits whitespace after certain tokens (e.g.,
- NoWhitespaceBefore
- Purpose: Prohibits whitespace before certain tokens (e.g.,
;
). - Example Violation:
int x = 1 ;
- Why Flagged: Space before
;
.
- Purpose: Prohibits whitespace before certain tokens (e.g.,
- OperatorWrap
- Purpose: Ensures operators are on the correct line.
- Example Violation:
int x = 1 + 2;
- Why Flagged:
+
should be at the end of the first line.
- ParenPad
- Purpose: Checks spacing inside parentheses.
- Example Violation:
if ( x == y ) {}
- Why Flagged: Spaces inside
(
and)
are incorrect.
- TypecastParenPad
- Purpose: Ensures spacing in typecasts.
- Example Violation:
Object o = ( String ) obj;
- Why Flagged: Spaces inside
( String )
are incorrect.
- WhitespaceAfter
- Purpose: Requires whitespace after certain tokens (e.g., commas).
- Example Violation:
int[] arr = {1,2,3};
- Why Flagged: Missing space after commas.
- WhitespaceAround
- Purpose: Ensures whitespace around operators/keywords.
- Example Violation:
if(x==y) {}
- Why Flagged: Missing spaces around
==
andif
.
Modifier Checks
These regulate Java modifiers.
- ModifierOrder
- Purpose: Ensures modifiers are in correct order (per JLS).
- Example Violation:
static public final int x = 1;
- Why Flagged: Incorrect order; should be
public static final
.
- RedundantModifier
- Purpose: Flags unnecessary modifiers.
- Example Violation:
public final class MyClass { public final void myMethod() {} }
- Why Flagged:
final
on method in afinal
class is redundant.
Block Checks
These enforce proper use of code blocks.
- AvoidNestedBlocks
- Purpose: Prohibits unnecessary nested blocks.
- Example Violation:
public void myMethod() { { int x = 1; } }
- Why Flagged: Unnecessary nested block.
- EmptyBlock
- Purpose: Flags empty blocks.
- Example Violation:
if (x == 1) {}
- Why Flagged: Empty
if
block.
- LeftCurly
- Purpose: Ensures opening braces are placed correctly.
- Example Violation:
public class MyClass { }
- Why Flagged:
{
should be on the same line asclass
.
- NeedBraces
- Purpose: Requires braces for single-statement blocks.
- Example Violation:
if (x == 1) y = 2;
- Why Flagged: Missing braces; should be
{ y = 2; }
.
- RightCurly
- Purpose: Ensures closing braces are placed correctly.
- Example Violation:
public class MyClass { }
- Why Flagged:
}
should be on a new line (depending on style).
Coding Problem Checks
These identify common coding issues.
- EmptyStatement
- Purpose: Flags empty statements.
- Example Violation:
int x = 1;; // Extra semicolon
- Why Flagged: Extra
;
creates an empty statement.
- EqualsHashCode
- Purpose: Ensures
equals()
andhashCode()
are both overridden. - Example Violation:
public class MyClass { @Override public boolean equals(Object o) { return true; } }
- Why Flagged: Missing
hashCode()
override.
- Purpose: Ensures
- HiddenField
- Purpose: Detects fields shadowed by local variables/parameters.
- Example Violation:
public class MyClass { int x; public void setX(int x) { this.x = x; } }
- Why Flagged: Parameter
x
shadows fieldx
.
- IllegalInstantiation
- Purpose: Prohibits instantiation of certain classes.
- Example Violation:
String s = new String("test");
- Why Flagged: Unnecessary instantiation of
String
.
- InnerAssignment
- Purpose: Disallows assignments in expressions.
- Example Violation:
if (x = 1) {}
- Why Flagged: Assignment
x = 1
in expression.
- MagicNumber
- Purpose: Flags hardcoded numeric literals.
- Example Violation:
int x = 42;
- Why Flagged:
42
should be a named constant (e.g.,static final int MY_CONST = 42;
).
- MissingSwitchDefault
- Purpose: Requires a
default
case inswitch
statements. - Example Violation:
switch (x) { case 1: break; }
- Why Flagged: Missing
default
case.
- Purpose: Requires a
- MultipleVariableDeclarations
- Purpose: Prohibits multiple variables in one declaration.
- Example Violation:
int x, y;
- Why Flagged: Should be
int x; int y;
.
- SimplifyBooleanExpression
- Purpose: Flags complex boolean expressions.
- Example Violation:
if (x == true) {}
- Why Flagged: Should be
if (x)
.
- SimplifyBooleanReturn
- Purpose: Simplifies boolean return statements.
- Example Violation:
if (x) return true; else return false;
- Why Flagged: Should be
return x;
.
Class Design Checks
These enforce good class design.
- DesignForExtension
- Purpose: Ensures non-final classes have protected/abstract methods.
- Example Violation:
public class MyClass { public void myMethod() {} }
- Why Flagged: Non-final class has non-protected/abstract method.
- FinalClass
- Purpose: Flags classes with private constructors as candidates for
final
. - Example Violation:
public class MyClass { private MyClass() {} }
- Why Flagged: Should be
final
since it can’t be extended.
- Purpose: Flags classes with private constructors as candidates for
- HideUtilityClassConstructor
- Purpose: Ensures utility classes have private constructors.
- Example Violation:
public class MyUtils { public static void doSomething() {} }
- Why Flagged: Missing private constructor for utility class.
- InterfaceIsType
- Purpose: Prohibits marker interfaces (without methods).
- Example Violation:
public interface MyMarker {}
- Why Flagged: Interface has no methods.
- VisibilityModifier
- Purpose: Enforces proper field visibility (prefers private with getters/setters).
- Example Violation:
public class MyClass { public int x; }
- Why Flagged: Field
x
should beprivate
with accessors.
Miscellaneous Checks
Additional checks for code quality.
- ArrayTypeStyle
- Purpose: Enforces consistent array declaration style (
int[]
vs.int []
). - Example Violation:
int x[];
- Why Flagged: Should be
int[] x
.
- Purpose: Enforces consistent array declaration style (
- FinalParameters
- Purpose: Requires method parameters to be
final
where possible. - Example Violation:
public void myMethod(int x) {}
- Why Flagged: Parameter
x
should befinal int x
.
- Purpose: Requires method parameters to be
- TodoComment
- Purpose: Flags
TODO
comments. - Example Violation:
// TODO: Fix this public void myMethod() {}
- Why Flagged:
TODO
comment detected.
- Purpose: Flags
- UpperEll
- Purpose: Ensures
L
for long literals (notl
). - Example Violation:
long x = 100l;
- Why Flagged:
100l
should be100L
.
- Purpose: Ensures
Suppression Filters (Inside TreeWalker)
These allow suppression within the AST.
- SuppressionXpathFilter
- Purpose: Suppresses checks using XPath expressions from a file (e.g.,
checkstyle-xpath-suppressions.xml
). - Example Violation: Similar to
SuppressionFilter
but uses XPath (e.g., suppressJavadocMethod
for a specific method).
- Purpose: Suppresses checks using XPath expressions from a file (e.g.,
- SuppressWarningsHolder
- Purpose: Supports
@SuppressWarnings("checkstyle:...")
in the AST. - Example Violation:
public class MyClass { int MY_FIELD; // Violates MemberName }
@SuppressWarnings("checkstyle:MemberName") public class MyClass { int MY_FIELD; // No violation }
- Why Flagged: Without suppression,
MY_FIELD
violatesMemberName
.
- Purpose: Supports
Key Notes
- Configurability: Rules like
LineLength
orMethodLength
can have custom thresholds (e.g.,max="120"
forLineLength
). - Suppression: Use
@SuppressWarnings("checkstyle:<check-name>")
or suppression files to bypass specific checks. - Integration: Run with Maven/Gradle or IDE plugins; errors are reported during builds.
- Header Check: Inactive unless uncommented and configured with
checkstyle.header.file
.
If you need specific customization examples (e.g., changing LineLength
to 120), violation fixes, or integration details, let me know!