Rules which enforce a specific coding style.
Table of Contents

AtLeastOneConstructor

Since: PMD 1.04

Priority: Medium (3)

Each non-static class should declare at least one constructor. Classes with solely static members are ignored, refer to UseUtilityClassRule to detect those.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.AtLeastOneConstructorRule

Example(s):

public class Foo {
   // missing constructor
  public void doSomething() { ... }
  public void doOtherThing { ... }
}

This rule has the following properties:

Name Default Value Description
ignoredAnnotations lombok.Data , lombok.Value , lombok.Builder , lombok.NoArgsConstructor , lombok.RequiredArgsConstructor , lombok.AllArgsConstructor Fully qualified names of the annotation types that should be ignored by this rule

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/AtLeastOneConstructor" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/AtLeastOneConstructor">
    <properties>
        <property name="ignoredAnnotations" value="lombok.Data,lombok.Value,lombok.Builder,lombok.NoArgsConstructor,lombok.RequiredArgsConstructor,lombok.AllArgsConstructor" />
    </properties>
</rule>

AvoidDollarSigns

Since: PMD 1.5

Priority: Medium (3)

Avoid using dollar signs in variable/method/class/interface names.

This rule is defined by the following XPath expression:

//ClassDeclaration           [contains(@SimpleName, '$')]
    | //EnumDeclaration            [contains(@SimpleName, '$')]
    | //AnnotationTypeDeclaration  [contains(@SimpleName, '$')]
    | //RecordDeclaration          [contains(@SimpleName, '$')]
    | //VariableId                 [contains(@Name, '$')]
    | //MethodDeclaration          [contains(@Name, '$')]

Example(s):

public class Fo$o {  // not a recommended name
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/AvoidDollarSigns" />

AvoidProtectedFieldInFinalClass

Since: PMD 2.1

Priority: Medium (3)

Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead.

This rule is defined by the following XPath expression:

//ClassDeclaration[@Final = true()]
/ClassBody
/FieldDeclaration[@Visibility = "protected"]

Example(s):

public final class Bar {
  private int x;
  protected int y;  // bar cannot be subclassed, so is y really private or package visible?
  Bar() {}
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/AvoidProtectedFieldInFinalClass" />

AvoidProtectedMethodInFinalClassNotExtending

Since: PMD 5.1

Priority: Medium (3)

Do not use protected methods in most final classes since they cannot be subclassed. This should only be allowed in final classes that extend other classes with protected methods (whose visibility cannot be reduced). Clarify your intent by using private or package access modifiers instead.

This rule is defined by the following XPath expression:

//ClassDeclaration[@Final= true() and not(ExtendsList)]
/ClassBody
/MethodDeclaration[@Visibility="protected" and @Name != 'finalize']

Example(s):

public final class Foo {
  private int bar() {}
  protected int baz() {} // Foo cannot be subclassed, and doesn't extend anything, so is baz() really private or package visible?
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/AvoidProtectedMethodInFinalClassNotExtending" />

AvoidUsingNativeCode

Since: PMD 4.1

Priority: Medium High (2)

Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability and increases the maintenance burden.

This rule is defined by the following XPath expression:

//MethodCall[TypeExpression/ClassType[pmd-java:typeIs('java.lang.System')]
                                    and @MethodName = 'loadLibrary']

Example(s):

public class SomeJNIClass {

     public SomeJNIClass() {
         System.loadLibrary("nativelib");
     }

     static {
         System.loadLibrary("nativelib");
     }

     public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
         System.loadLibrary("nativelib");
     }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/AvoidUsingNativeCode" />

BooleanGetMethodName

Since: PMD 4.0

Priority: Medium Low (4)

Methods that return boolean results should be named as predicate statements to denote this. I.e, ‘isReady()’, ‘hasValues()’, ‘canCommit()’, ‘willFail()’, etc. Avoid the use of the ‘get’ prefix for these methods.

This rule is defined by the following XPath expression:

//MethodDeclaration
    [starts-with(@Name, 'get')]
    [@Arity = 0 or $checkParameterizedMethods = true()]
    [ PrimitiveType[@Kind = 'boolean'] and @Overridden = false() ]

Example(s):

public boolean getFoo();            // bad
public boolean isFoo();             // ok
public boolean getFoo(boolean bar); // ok, unless checkParameterizedMethods=true

This rule has the following properties:

Name Default Value Description
checkParameterizedMethods false Check parameterized methods

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/BooleanGetMethodName" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/BooleanGetMethodName">
    <properties>
        <property name="checkParameterizedMethods" value="false" />
    </properties>
</rule>

CallSuperInConstructor

Since: PMD 3.0

Priority: Medium (3)

It is a good practice to call super() in a constructor. If super() is not called but another constructor (such as an overloaded constructor) is called, this rule will not report it.

This rule is defined by the following XPath expression:

//ClassDeclaration[ExtendsList/*]
  /ClassBody
  /ConstructorDeclaration[ not(Block/ExplicitConstructorInvocation) ]

Example(s):

public class Foo extends Bar{
  public Foo() {
   // call the constructor of Bar
   super();
  }
 public Foo(int code) {
  // do something with code
   this();
   // no problem with this
  }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/CallSuperInConstructor" />

ClassNamingConventions

Since: PMD 1.2

Priority: High (1)

Configurable naming conventions for type declarations. This rule reports type declarations which do not match the regex that applies to their specific kind (e.g. enum or interface). Each regex can be configured through properties.

By default, this rule uses the standard Java naming convention (Pascal case).

The rule can detect utility classes and enforce a different naming convention on those. E.g. setting the property utilityClassPattern to [A-Z][a-zA-Z0-9]+(Utils?|Helper|Constants) reports any utility class, whose name does not end in "Util(s)", "Helper" or "Constants".

For this rule, a utility class is defined as: a concrete class that does not inherit from a super class or implement any interface and only has static fields or methods.

This rule detects test classes using the following convention: Test classes are top-level classes, that either inherit from JUnit 3 TestCase or have at least one method annotated with the Test annotations from JUnit4/5 or TestNG.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.ClassNamingConventionsRule

Example(s):

// This is Pascal case, the recommended naming convention in Java
// Note that the default values of this rule don't allow underscores
// or accented characters in type names
public class FooBar {}

// You may want abstract classes to be named 'AbstractXXX',
// in which case you can customize the regex for abstract
// classes to 'Abstract[A-Z]\w+'
public abstract class Thing {}

// This class doesn't respect the convention, and will be flagged
public class Éléphant {}

This rule has the following properties:

Name Default Value Description
classPattern [A-Z][a-zA-Z0-9]* Regex which applies to concrete class names
abstractClassPattern [A-Z][a-zA-Z0-9]* Regex which applies to abstract class names
interfacePattern [A-Z][a-zA-Z0-9]* Regex which applies to interface names
enumPattern [A-Z][a-zA-Z0-9]* Regex which applies to enum names
annotationPattern [A-Z][a-zA-Z0-9]* Regex which applies to annotation names
utilityClassPattern [A-Z][a-zA-Z0-9]* Regex which applies to utility class names
testClassPattern ^Test.*$|^[A-Z][a-zA-Z0-9]*Test(s|Case)?$ Regex which applies to test class names. Since PMD 6.52.0.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/ClassNamingConventions" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/ClassNamingConventions">
    <properties>
        <property name="classPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="abstractClassPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="interfacePattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="enumPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="annotationPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="utilityClassPattern" value="[A-Z][a-zA-Z0-9]*" />
        <property name="testClassPattern" value="^Test.*$|^[A-Z][a-zA-Z0-9]*Test(s|Case)?$" />
    </properties>
</rule>

CommentDefaultAccessModifier

Since: PMD 5.4.0

Priority: Medium (3)

To avoid mistakes if we want that an Annotation, Class, Enum, Method, Constructor or Field have a default access modifier we must add a comment at the beginning of its declaration. By default, the comment must be /* default */ or /* package */, if you want another, you have to provide a regular expression.

This rule ignores by default all cases that have a @VisibleForTesting annotation or any JUnit5/TestNG annotation. Use the property "ignoredAnnotations" to customize the recognized annotations.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.CommentDefaultAccessModifierRule

Example(s):

public class Foo {
    final String stringValue = "some string";
    String getString() {
       return stringValue;
    }

    class NestedFoo {
    }
}

// should be
public class Foo {
    /* default */ final String stringValue = "some string";
    /* default */ String getString() {
       return stringValue;
    }

    /* default */ class NestedFoo {
    }
}

This rule has the following properties:

Name Default Value Description
ignoredAnnotations android.support.annotation.VisibleForTesting , co.elastic.clients.util.VisibleForTesting , com.google.common.annotations.VisibleForTesting , org.junit.jupiter.api.AfterAll , org.junit.jupiter.api.AfterEach , org.junit.jupiter.api.BeforeAll , org.junit.jupiter.api.BeforeEach , org.junit.jupiter.api.RepeatedTest , org.junit.jupiter.api.Test , org.junit.jupiter.api.TestFactory , org.junit.jupiter.api.TestTemplate , org.junit.jupiter.api.extension.RegisterExtension , org.junit.jupiter.params.ParameterizedTest , org.testng.annotations.AfterClass , org.testng.annotations.AfterGroups , org.testng.annotations.AfterMethod , org.testng.annotations.AfterSuite , org.testng.annotations.AfterTest , org.testng.annotations.BeforeClass , org.testng.annotations.BeforeGroups , org.testng.annotations.BeforeMethod , org.testng.annotations.BeforeSuite , org.testng.annotations.BeforeTest , org.testng.annotations.Test Fully qualified names of the annotation types that should be ignored by this rule
regex \/\*\s*(default|package)\s*\*\/ Regular expression
checkTopLevelTypes false Check for default access modifier in top-level classes, annotations, and enums

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/CommentDefaultAccessModifier" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/CommentDefaultAccessModifier">
    <properties>
        <property name="ignoredAnnotations" value="android.support.annotation.VisibleForTesting,co.elastic.clients.util.VisibleForTesting,com.google.common.annotations.VisibleForTesting,org.junit.jupiter.api.AfterAll,org.junit.jupiter.api.AfterEach,org.junit.jupiter.api.BeforeAll,org.junit.jupiter.api.BeforeEach,org.junit.jupiter.api.RepeatedTest,org.junit.jupiter.api.Test,org.junit.jupiter.api.TestFactory,org.junit.jupiter.api.TestTemplate,org.junit.jupiter.api.extension.RegisterExtension,org.junit.jupiter.params.ParameterizedTest,org.testng.annotations.AfterClass,org.testng.annotations.AfterGroups,org.testng.annotations.AfterMethod,org.testng.annotations.AfterSuite,org.testng.annotations.AfterTest,org.testng.annotations.BeforeClass,org.testng.annotations.BeforeGroups,org.testng.annotations.BeforeMethod,org.testng.annotations.BeforeSuite,org.testng.annotations.BeforeTest,org.testng.annotations.Test" />
        <property name="regex" value="\/\*\s*(default|package)\s*\*\/" />
        <property name="checkTopLevelTypes" value="false" />
    </properties>
</rule>

ConfusingTernary

Since: PMD 1.9

Priority: Medium (3)

Avoid negation within an "if" expression with an "else" clause. For example, rephrase: if (x != y) diff(); else same(); as: if (x == y) same(); else diff();.

Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?".

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.ConfusingTernaryRule

Example(s):

boolean bar(int x, int y) {
    return (x != y) ? diff : same;
}

This rule has the following properties:

Name Default Value Description
ignoreElseIf false Ignore conditions with an else-if case

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/ConfusingTernary" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/ConfusingTernary">
    <properties>
        <property name="ignoreElseIf" value="false" />
    </properties>
</rule>

ControlStatementBraces

Since: PMD 6.2.0

Priority: Medium (3)

Enforce a policy for braces on control statements. It is recommended to use braces on ‘if … else’ statements and loop statements, even if they are optional. This usually makes the code clearer, and helps prepare the future when you need to add another statement. That said, this rule lets you control which statements are required to have braces via properties.

From 6.2.0 on, this rule supersedes WhileLoopMustUseBraces, ForLoopMustUseBraces, IfStmtMustUseBraces, and IfElseStmtMustUseBraces.

This rule is defined by the following XPath expression:

//WhileStatement[$checkWhileStmt and not(Block) and not($allowEmptyLoop and EmptyStatement)]
                |
                //ForStatement[$checkForStmt and not(Block) and not($allowEmptyLoop and EmptyStatement)]
                |
                //ForeachStatement[$checkForStmt and not(Block) and not($allowEmptyLoop and EmptyStatement)]
                |
                //DoStatement[$checkDoWhileStmt and not(Block) and not($allowEmptyLoop and EmptyStatement)]
                |
                (: The violation is reported on the sub statement -- not the if statement :)
                //IfStatement[$checkIfElseStmt]
                    /*[position() > 1 and not(self::Block or self::IfStatement)]
                      [ $checkSingleIfStmt
                            (: Inside this (...) is the definition of a "single if statement" :)
                            or not(parent::*/@Else = false() (: No else stmt :)
                                   (: Not the last branch of an 'if ... else if' chain :)
                                   and not(parent::IfStatement[parent::IfStatement]))]

                |
                (: Reports case labels if one of their subordinate statements is not braced :)
                //SwitchFallthroughBranch[$checkCaseStmt]
                             [count(*) > 1 and (count(*) > 2 or not(child::*[2]/self::Block))]

Example(s):

while (true)    // not recommended
  x++;

while (true) {  // preferred approach
  x++;
}

This rule has the following properties:

Name Default Value Description
checkIfElseStmt true Require that ‘if … else’ statements use braces
checkSingleIfStmt true Require that ‘if’ statements with a single branch use braces
checkWhileStmt true Require that ‘while’ loops use braces
checkForStmt true Require that ‘for’ loops should use braces
checkDoWhileStmt true Require that ‘do … while’ loops use braces
checkCaseStmt false Require that cases of a switch have braces
allowEmptyLoop false Allow loops with an empty statement, e.g. ‘while(true);’

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/ControlStatementBraces" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/ControlStatementBraces">
    <properties>
        <property name="checkIfElseStmt" value="true" />
        <property name="checkSingleIfStmt" value="true" />
        <property name="checkWhileStmt" value="true" />
        <property name="checkForStmt" value="true" />
        <property name="checkDoWhileStmt" value="true" />
        <property name="checkCaseStmt" value="false" />
        <property name="allowEmptyLoop" value="false" />
    </properties>
</rule>

EmptyControlStatement

Since: PMD 6.46.0

Priority: Medium (3)

Reports control statements whose body is empty, as well as empty initializers.

The checked code constructs are the following:

  • bodies of try statements
  • finally clauses of try statements
  • switch statements
  • synchronized statements
  • if statements
  • loop statements: while, for, do .. while
  • initializers
  • blocks used as statements (for scoping)

This rule replaces the rules EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, and EmptyWhileStmt.

Notice that EmptyCatchBlock is still an independent rule.

EmptyStatementNotInLoop is replaced by UnnecessarySemicolon.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.EmptyControlStatementRule

Example(s):

class Foo {
    {
        if (true); // empty if statement
        if (true) { // empty as well
        }
    }

    {} // empty initializer
}

This rule has the following properties:

Name Default Value Description
allowCommentedBlocks false Option for allowing empty but commented blocks. This is useful where a developer wants to have the code structure and explain why a condition does not require logic or to hold TODO comments for future work.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/EmptyControlStatement" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/EmptyControlStatement">
    <properties>
        <property name="allowCommentedBlocks" value="false" />
    </properties>
</rule>

EmptyMethodInAbstractClassShouldBeAbstract

Since: PMD 4.1

Priority: High (1)

Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to remove their inapproprate usage by developers who should be implementing their own versions in the concrete subclasses.

This rule is defined by the following XPath expression:

//ClassDeclaration[@RegularClass = true() and pmd-java:modifiers() = "abstract"]
    /ClassBody
    /MethodDeclaration
    [Block[
      let $size := count(*[not(self::EmptyStatement)])
      return $size = 0
             or $size = 1 and ReturnStatement[ NullLiteral or NumericLiteral[@ValueAsInt = 0] or StringLiteral[@Empty = true()]]
    ]]

Example(s):

public abstract class ShouldBeAbstract {
    public Object couldBeAbstract() {
        // Should be abstract method ?
        return null;
    }

    public void couldBeAbstract() {
    }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/EmptyMethodInAbstractClassShouldBeAbstract" />

ExtendsObject

Since: PMD 5.0

Priority: Medium Low (4)

No need to explicitly extend Object.

This rule is defined by the following XPath expression:

//ExtendsList/ClassType[pmd-java:typeIsExactly('java.lang.Object')]

Example(s):

public class Foo extends Object {     // not required
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/ExtendsObject" />

FieldDeclarationsShouldBeAtStartOfClass

Since: PMD 5.0

Priority: Medium (3)

Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.FieldDeclarationsShouldBeAtStartOfClassRule

Example(s):

public class HelloWorldBean {

  // Field declared before methods / inner classes - OK
  private String _thing;

  public String getMessage() {
    return "Hello World!";
  }

  // Field declared after methods / inner classes - avoid this
  private String _fieldInWrongLocation;
}

This rule has the following properties:

Name Default Value Description
ignoreAnonymousClassDeclarations true Ignore field declarations, that are initialized with an anonymous class creation expression
ignoreInterfaceDeclarations false Ignore interface declarations that precede fields
ignoreEnumDeclarations true Ignore enum declarations that precede fields

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/FieldDeclarationsShouldBeAtStartOfClass" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/FieldDeclarationsShouldBeAtStartOfClass">
    <properties>
        <property name="ignoreAnonymousClassDeclarations" value="true" />
        <property name="ignoreInterfaceDeclarations" value="false" />
        <property name="ignoreEnumDeclarations" value="true" />
    </properties>
</rule>

FieldNamingConventions

Since: PMD 6.7.0

Priority: High (1)

Configurable naming conventions for field declarations. This rule reports variable declarations which do not match the regex that applies to their specific kind —e.g. constants (static final), enum constant, final field. Each regex can be configured through properties.

By default this rule uses the standard Java naming convention (Camel case), and uses the ALL_UPPER convention for constants and enum constants.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.FieldNamingConventionsRule

Example(s):

class Foo {
                int myField = 1; // This is in camel case, so it's ok
                int my_Field = 1; // This contains an underscore, it's not ok by default
                                  // but you may allow it, or even require the "my_" prefix

                final int FinalField = 1; // you may configure a different convention for final fields,
                                          // e.g. here PascalCase: [A-Z][a-zA-Z0-9]*

                interface Interface {
                    double PI = 3.14; // interface "fields" use the constantPattern property
                }

                enum AnEnum {
                    ORG, NET, COM; // These use a separate property but are set to ALL_UPPER by default
                }
            }

This rule has the following properties:

Name Default Value Description
publicConstantPattern [A-Z][A-Z_0-9]* Regex which applies to public constant names
constantPattern [A-Z][A-Z_0-9]* Regex which applies to non-public static final field names
enumConstantPattern [A-Z][A-Z_0-9]* Regex which applies to enum constant names
finalFieldPattern [a-z][a-zA-Z0-9]* Regex which applies to final field names
staticFieldPattern [a-z][a-zA-Z0-9]* Regex which applies to static field names
defaultFieldPattern [a-z][a-zA-Z0-9]* Regex which applies to field names
exclusions serialVersionUID , serialPersistentFields Names of fields to whitelist.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/FieldNamingConventions" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/FieldNamingConventions">
    <properties>
        <property name="publicConstantPattern" value="[A-Z][A-Z_0-9]*" />
        <property name="constantPattern" value="[A-Z][A-Z_0-9]*" />
        <property name="enumConstantPattern" value="[A-Z][A-Z_0-9]*" />
        <property name="finalFieldPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="staticFieldPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="defaultFieldPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="exclusions" value="serialVersionUID,serialPersistentFields" />
    </properties>
</rule>

FinalParameterInAbstractMethod

Since: PMD 6.42.0

Priority: High (1)

Declaring a method parameter as final for an interface method is useless because the implementation may choose to not respect it.

This rule is defined by the following XPath expression:

//MethodDeclaration
    [FormalParameters/FormalParameter[@Final = true()]]
    [not(Block)]

Example(s):

public interface MyInterface {
  void process(final Object arg); // Avoid using final here
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/FinalParameterInAbstractMethod" />

ForLoopShouldBeWhileLoop

Since: PMD 1.02

Priority: Medium (3)

Some for loops can be simplified to while loops, this makes them more concise.

This rule is defined by the following XPath expression:

//ForStatement[not(ForInit | ForUpdate) and count(*) = 2]

Example(s):

public class Foo {
    void bar() {
        for (;true;) true; // No Init or Update part, may as well be: while (true)
    }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/ForLoopShouldBeWhileLoop" />

FormalParameterNamingConventions

Since: PMD 6.6.0

Priority: High (1)

Configurable naming conventions for formal parameters of methods and lambdas. This rule reports formal parameters which do not match the regex that applies to their specific kind (e.g. lambda parameter, or final formal parameter). Each regex can be configured through properties.

By default this rule uses the standard Java naming convention (Camel case).

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.FormalParameterNamingConventionsRule

Example(s):

class Foo {

                abstract void bar(int myInt); // This is Camel case, so it's ok

                void bar(int my_i) { // this will be reported

                }

                void lambdas() {

                    // lambdas parameters can be configured separately
                    Consumer<String> lambda1 = s_str -> { };

                    // lambda parameters with an explicit type can be configured separately
                    Consumer<String> lambda1 = (String str) -> { };

                }

            }

This rule has the following properties:

Name Default Value Description
methodParameterPattern [a-z][a-zA-Z0-9]* Regex which applies to formal parameter names
finalMethodParameterPattern [a-z][a-zA-Z0-9]* Regex which applies to final formal parameter names
lambdaParameterPattern [a-z][a-zA-Z0-9]* Regex which applies to inferred-type lambda parameter names
explicitLambdaParameterPattern [a-z][a-zA-Z0-9]* Regex which applies to explicitly-typed lambda parameter names

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/FormalParameterNamingConventions" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/FormalParameterNamingConventions">
    <properties>
        <property name="methodParameterPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="finalMethodParameterPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="lambdaParameterPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="explicitLambdaParameterPattern" value="[a-z][a-zA-Z0-9]*" />
    </properties>
</rule>

GenericsNaming

Since: PMD 4.2.6

Priority: Medium Low (4)

Names for references to generic values should be limited to a single uppercase letter.

This rule is defined by the following XPath expression:

//TypeParameter[
  string-length(@Name) > 1
  or
  upper-case(@Name) != @Name
]

Example(s):

public interface GenericDao<E extends BaseModel, K extends Serializable> extends BaseDao {
    // This is ok...
}

public interface GenericDao<E extends BaseModel, K extends Serializable> {
    // Also this
}

public interface GenericDao<e extends BaseModel, K extends Serializable> {
    // 'e' should be an 'E'
}

public interface GenericDao<EF extends BaseModel, K extends Serializable> {
   // 'EF' is not ok.
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/GenericsNaming" />

IdenticalCatchBranches

Since: PMD 6.4.0

Priority: Medium (3)

Minimum Language Version: Java 1.7

Identical catch branches use up vertical space and increase the complexity of code without adding functionality. It’s better style to collapse identical branches into a single multi-catch branch.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.IdenticalCatchBranchesRule

Example(s):

try {
    // do something
} catch (IllegalArgumentException e) {
    throw e;
} catch (IllegalStateException e) { // Can be collapsed into the previous block
    throw e;
}

try {
    // do something
} catch (IllegalArgumentException | IllegalStateException e) { // This is better
    throw e;
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/IdenticalCatchBranches" />

LinguisticNaming

Since: PMD 6.7.0

Priority: Medium (3)

This rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they should be boolean but have a different type. It also checks for methods, that according to their name, should return a boolean, but don’t. Further, it checks, that getters return something and setters won’t. Finally, it checks that methods, that start with "to" - so called transform methods - actually return something, since according to their name, they should convert or transform one object into another. There is additionally an option, to check for methods that contain "To" in their name - which are also transform methods. However, this is disabled by default, since this detection is prone to false positives.

For more information, see Linguistic Antipatterns - What They Are and How Developers Perceive Them.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.LinguisticNamingRule

Example(s):

public class LinguisticNaming {
    int isValid;    // the field name indicates a boolean, but it is an int.
    boolean isTrue; // correct type of the field

    void myMethod() {
        int hasMoneyLocal;      // the local variable name indicates a boolean, but it is an int.
        boolean hasSalaryLocal; // correct naming and type
    }

    // the name of the method indicates, it is a boolean, but the method returns an int.
    int isValid() {
        return 1;
    }
    // correct naming and return type
    boolean isSmall() {
        return true;
    }

    // the name indicates, this is a setter, but it returns something
    int setName() {
        return 1;
    }

    // the name indicates, this is a getter, but it doesn't return anything
    void getName() {
        // nothing to return?
    }

    // the name indicates, it transforms an object and should return the result
    void toDataType() {
        // nothing to return?
    }
    // the name indicates, it transforms an object and should return the result
    void grapeToWine() {
        // nothing to return?
    }
}

This rule has the following properties:

Name Default Value Description
ignoredAnnotations java.lang.Override Fully qualified names of the annotation types that should be ignored by this rule
checkBooleanMethod true Check method names and types for inconsistent naming.
checkGetters true Check return type of getters.
checkSetters true Check return type of setters.
checkPrefixedTransformMethods true Check return type of methods whose names start with the configured prefix (see transformMethodNames property).
checkTransformMethods false Check return type of methods which contain the configured infix in their name (see transformMethodNames property).
booleanMethodPrefixes is , has , can , have , will , should The prefixes of methods that return boolean.
transformMethodNames to , as The prefixes and infixes that indicate a transform method.
checkFields true Check field names and types for inconsistent naming.
checkVariables true Check local variable names and types for inconsistent naming.
booleanFieldPrefixes is , has , can , have , will , should The prefixes of fields and variables that indicate boolean.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/LinguisticNaming" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/LinguisticNaming">
    <properties>
        <property name="ignoredAnnotations" value="java.lang.Override" />
        <property name="checkBooleanMethod" value="true" />
        <property name="checkGetters" value="true" />
        <property name="checkSetters" value="true" />
        <property name="checkPrefixedTransformMethods" value="true" />
        <property name="checkTransformMethods" value="false" />
        <property name="booleanMethodPrefixes" value="is,has,can,have,will,should" />
        <property name="transformMethodNames" value="to,as" />
        <property name="checkFields" value="true" />
        <property name="checkVariables" value="true" />
        <property name="booleanFieldPrefixes" value="is,has,can,have,will,should" />
    </properties>
</rule>

LocalHomeNamingConvention

Since: PMD 4.0

Priority: Medium Low (4)

The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’.

This rule is defined by the following XPath expression:

//ClassDeclaration
[
    pmd-java:typeIs('javax.ejb.EJBLocalHome')
    and not(ends-with(@SimpleName, 'LocalHome'))
]

Example(s):

public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {} // proper name

public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {}  // non-standard name

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/LocalHomeNamingConvention" />

LocalInterfaceSessionNamingConvention

Since: PMD 4.0

Priority: Medium Low (4)

The Local Interface of a Session EJB should be suffixed by ‘Local’.

This rule is defined by the following XPath expression:

//ClassDeclaration
[
    pmd-java:typeIs('javax.ejb.EJBLocalObject')
    and not(ends-with(@SimpleName, 'Local'))
]

Example(s):

public interface MyLocal extends javax.ejb.EJBLocalObject {}                // proper name

public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {}    // non-standard name

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/LocalInterfaceSessionNamingConvention" />

LocalVariableCouldBeFinal

Since: PMD 2.2

Priority: Medium (3)

A local variable assigned only once can be declared final.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.LocalVariableCouldBeFinalRule

Example(s):

public class Bar {
    public void foo () {
    String txtA = "a";          // if txtA will not be assigned again it is better to do this:
    final String txtB = "b";
    }
}

This rule has the following properties:

Name Default Value Description
ignoreForEachDecl false Ignore non-final loop variables in a for-each statement.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/LocalVariableCouldBeFinal" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/LocalVariableCouldBeFinal">
    <properties>
        <property name="ignoreForEachDecl" value="false" />
    </properties>
</rule>

LocalVariableNamingConventions

Since: PMD 6.6.0

Priority: High (1)

Configurable naming conventions for local variable declarations and other locally-scoped variables. This rule reports variable declarations which do not match the regex that applies to their specific kind (e.g. final variable, or catch-clause parameter). Each regex can be configured through properties.

By default this rule uses the standard Java naming convention (Camel case).

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.LocalVariableNamingConventionsRule

Example(s):

class Foo {
                void bar() {
                    int localVariable = 1; // This is in camel case, so it's ok
                    int local_variable = 1; // This will be reported unless you change the regex

                    final int i_var = 1; // final local variables can be configured separately

                    try {
                        foo();
                    } catch (IllegalArgumentException e_illegal) {
                        // exception block parameters can be configured separately
                    }

                }
            }

This rule has the following properties:

Name Default Value Description
localVarPattern [a-z][a-zA-Z0-9]* Regex which applies to non-final local variable names
finalVarPattern [a-z][a-zA-Z0-9]* Regex which applies to final local variable names
catchParameterPattern [a-z][a-zA-Z0-9]* Regex which applies to exception block parameter names

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/LocalVariableNamingConventions" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/LocalVariableNamingConventions">
    <properties>
        <property name="localVarPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="finalVarPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="catchParameterPattern" value="[a-z][a-zA-Z0-9]*" />
    </properties>
</rule>

LongVariable

Since: PMD 0.3

Priority: Medium (3)

Fields, formal arguments, or local variable names that are too long can make the code difficult to follow.

This rule is defined by the following XPath expression:

//VariableId[string-length(@Name) > $minimum]

Example(s):

public class Something {
    int reallyLongIntName = -3;             // VIOLATION - Field
    public static void main( String argumentsList[] ) { // VIOLATION - Formal
        int otherReallyLongName = -5;       // VIOLATION - Local
        for (int interestingIntIndex = 0;   // VIOLATION - For
             interestingIntIndex < 10;
             interestingIntIndex ++ ) {
    }
}

This rule has the following properties:

Name Default Value Description
minimum 17 The variable length reporting threshold

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/LongVariable" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/LongVariable">
    <properties>
        <property name="minimum" value="17" />
    </properties>
</rule>

MDBAndSessionBeanNamingConvention

Since: PMD 4.0

Priority: Medium Low (4)

The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’.

This rule is defined by the following XPath expression:

//ClassDeclaration
[
    (pmd-java:typeIs('javax.ejb.SessionBean')
     or pmd-java:typeIs('javax.ejb.MessageDrivenBean'))
    and not(ends-with(@SimpleName, 'Bean'))
]

Example(s):

public class SomeBean implements SessionBean{}                  // proper name

public class MissingTheProperSuffix implements SessionBean {}   // non-standard name

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/MDBAndSessionBeanNamingConvention" />

MethodArgumentCouldBeFinal

Since: PMD 2.2

Priority: Medium (3)

A method argument that is never re-assigned within the method can be declared final.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.MethodArgumentCouldBeFinalRule

Example(s):

public void foo1 (String param) {       // do stuff with param never assigning it

}

public void foo2 (final String param) { // better, do stuff with param never assigning it

}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/MethodArgumentCouldBeFinal" />

MethodNamingConventions

Since: PMD 1.2

Priority: High (1)

Configurable naming conventions for method declarations. This rule reports method declarations which do not match the regex that applies to their specific kind (e.g. JUnit test or native method). Each regex can be configured through properties.

By default this rule uses the standard Java naming convention (Camel case).

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.MethodNamingConventionsRule

Example(s):

public class Foo {
    public void fooStuff() {
    }
}

This rule has the following properties:

Name Default Value Description
methodPattern [a-z][a-zA-Z0-9]* Regex which applies to instance method names
staticPattern [a-z][a-zA-Z0-9]* Regex which applies to static method names
nativePattern [a-z][a-zA-Z0-9]* Regex which applies to native method names
junit3TestPattern test[A-Z0-9][a-zA-Z0-9]* Regex which applies to JUnit 3 test method names
junit4TestPattern [a-z][a-zA-Z0-9]* Regex which applies to JUnit 4 test method names
junit5TestPattern [a-z][a-zA-Z0-9]* Regex which applies to JUnit 5 test method names

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/MethodNamingConventions" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/MethodNamingConventions">
    <properties>
        <property name="methodPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="staticPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="nativePattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="junit3TestPattern" value="test[A-Z0-9][a-zA-Z0-9]*" />
        <property name="junit4TestPattern" value="[a-z][a-zA-Z0-9]*" />
        <property name="junit5TestPattern" value="[a-z][a-zA-Z0-9]*" />
    </properties>
</rule>

NoPackage

Since: PMD 3.3

Priority: Medium (3)

Detects when a class, interface, enum or annotation does not have a package definition.

This rule is defined by the following XPath expression:

/CompilationUnit[not(PackageDeclaration)]/*[pmd-java:nodeIs("TypeDeclaration")][1]

Example(s):

// no package declaration
public class ClassInDefaultPackage {
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/NoPackage" />

OnlyOneReturn

Since: PMD 1.0

Priority: Medium (3)

A method should have only one exit point, and that should be the last statement in the method.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.OnlyOneReturnRule

Example(s):

public class OneReturnOnly1 {
  public String foo(int x) {
    if (x > 0) {
      return "hey";   // first exit
    }
    return "hi";    // second exit
  }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/OnlyOneReturn" />

PackageCase

Since: PMD 3.3

Priority: Medium (3)

Detects when a package definition contains uppercase characters.

This rule is defined by the following XPath expression:

//PackageDeclaration[lower-case(@Name) != @Name]

Example(s):

package com.MyCompany;  // should be lowercase name

public class SomeClass {
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/PackageCase" />

PrematureDeclaration

Since: PMD 5.0

Priority: Medium (3)

Checks for variables that are defined before they might be used. A declaration is deemed to be premature if there are some statements that may return or throw an exception between the time the variable is declared and the time it is first read.

Some variables cannot be declared close to their first usage because of side-effects occurring before they’re first used. We try to avoid reporting those by considering most method and constructor invocations to be impure. See the second example.

Note that this rule is meant to improve code readability but is not an optimization. A smart JIT will not care whether the variable is declared prematurely or not, as it can reorder code.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.PrematureDeclarationRule

Example(s):

public int getLength(String[] strings) {

    int length = 0; // could be moved closer to the loop

    if (strings == null || strings.length == 0) return 0;

    for (String str : strings) {
        length += str.length();
    }

    return length;
}
public int getLength(String[] strings) {

    int startTime = System.nanoTime(); // cannot be moved because initializer is impure

    if (strings == null || strings.length == 0) {
        // some error logic
        throw new SomeException(...);
    }

    for (String str : strings) {
        length += str.length();
    }

    return System.nanoTime() - startTime;
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/PrematureDeclaration" />

RemoteInterfaceNamingConvention

Since: PMD 4.0

Priority: Medium Low (4)

Remote Interface of a Session EJB should not have a suffix.

This rule is defined by the following XPath expression:

//ClassDeclaration
[
    pmd-java:typeIs('javax.ejb.EJBObject')
    and matches(@SimpleName, '.*(Session|EJB|Bean)$')
]

Example(s):

/* Poor Session suffix */
public interface BadSuffixSession extends javax.ejb.EJBObject {}

/* Poor EJB suffix */
public interface BadSuffixEJB extends javax.ejb.EJBObject {}

/* Poor Bean suffix */
public interface BadSuffixBean extends javax.ejb.EJBObject {}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/RemoteInterfaceNamingConvention" />

RemoteSessionInterfaceNamingConvention

Since: PMD 4.0

Priority: Medium Low (4)

A Remote Home interface type of a Session EJB should be suffixed by ‘Home’.

This rule is defined by the following XPath expression:

//ClassDeclaration
[
    pmd-java:typeIs('javax.ejb.EJBHome')
    and not(ends-with(@SimpleName, 'Home'))
]

Example(s):

public interface MyBeautifulHome extends javax.ejb.EJBHome {}       // proper name

public interface MissingProperSuffix extends javax.ejb.EJBHome {}   // non-standard name

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/RemoteSessionInterfaceNamingConvention" />

ShortClassName

Since: PMD 5.0

Priority: Medium Low (4)

Short Classnames with fewer than e.g. five characters are not recommended.

This rule is defined by the following XPath expression:

//ClassDeclaration[string-length(@SimpleName) < $minimum]

Example(s):

public class Foo {
}

This rule has the following properties:

Name Default Value Description
minimum 5 Number of characters that are required as a minimum for a class name.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/ShortClassName" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/ShortClassName">
    <properties>
        <property name="minimum" value="5" />
    </properties>
</rule>

ShortMethodName

Since: PMD 0.3

Priority: Medium (3)

Method names that are very short are not helpful to the reader.

This rule is defined by the following XPath expression:

//MethodDeclaration[string-length(@Name) < $minimum]

Example(s):

public class ShortMethod {
    public void a( int i ) { // Violation
    }
}

This rule has the following properties:

Name Default Value Description
minimum 3 Number of characters that are required as a minimum for a method name.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/ShortMethodName" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/ShortMethodName">
    <properties>
        <property name="minimum" value="3" />
    </properties>
</rule>

ShortVariable

Since: PMD 0.3

Priority: Medium (3)

Fields, local variables, enum constant names or parameter names that are very short are not helpful to the reader.

This rule is defined by the following XPath expression:

//VariableId[string-length(@Name) < $minimum]
 (: ForStatement :)
 [not(../../parent::ForInit)]
 (: Foreach statement :)
 [not(../../parent::ForeachStatement)]
 (: Catch statement parameter :)
 [not(parent::CatchParameter)]
 (: Lambda expression parameter :)
 [not(parent::LambdaParameter)]

Example(s):

public class Something {
    private int q = 15;                         // field - too short
    public static void main( String as[] ) {    // formal arg - too short
        int r = 20 + q;                         // local var - too short
        for (int i = 0; i < 10; i++) {          // not a violation (inside 'for' loop)
            r += q;
        }
        for (Integer i : numbers) {             // not a violation (inside 'for-each' loop)
            r += q;
        }
    }
}

This rule has the following properties:

Name Default Value Description
minimum 3 Number of characters that are required as a minimum for a variable name.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/ShortVariable" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/ShortVariable">
    <properties>
        <property name="minimum" value="3" />
    </properties>
</rule>

TooManyStaticImports

Since: PMD 4.1

Priority: Medium (3)

If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (Sun 1.5 Language Guide).

This rule is defined by the following XPath expression:

.[count(ImportDeclaration[@Static = true()]) > $maximumStaticImports]

Example(s):

import static Lennon;
import static Ringo;
import static George;
import static Paul;
import static Yoko; // Too much !

This rule has the following properties:

Name Default Value Description
maximumStaticImports 4 All static imports can be disallowed by setting this to 0

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/TooManyStaticImports" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/TooManyStaticImports">
    <properties>
        <property name="maximumStaticImports" value="4" />
    </properties>
</rule>

UnnecessaryAnnotationValueElement

Since: PMD 6.2.0

Priority: Medium (3)

Avoid the use of value in annotations when it’s the only element.

This rule is defined by the following XPath expression:

//Annotation/AnnotationMemberList[count(*) = 1 and MemberValuePair[@Shorthand = false() and @Name = 'value']]

Example(s):

@TestClassAnnotation(value = "TEST")
public class Foo {

    @TestMemberAnnotation(value = "TEST")
    private String y;

    @TestMethodAnnotation(value = "TEST")
    public void bar() {
        int x = 42;
        return;
    }
}

// should be

@TestClassAnnotation("TEST")
public class Foo {

    @TestMemberAnnotation("TEST")
    private String y;

    @TestMethodAnnotation("TEST")
    public void bar() {
        int x = 42;
        return;
    }
}

This rule has the following properties:

Name Default Value Description
java7Compatibility false If disabled, the rule shows also violations that are applicable for java8+

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryAnnotationValueElement" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UnnecessaryAnnotationValueElement">
    <properties>
        <property name="java7Compatibility" value="false" />
    </properties>
</rule>

UnnecessaryBoxing

Since: PMD 7.0.0

Priority: Medium (3)

Minimum Language Version: Java 1.5

Reports explicit boxing and unboxing conversions that may safely be removed, either because they would be inserted by the compiler automatically, or because they’re semantically a noop (eg unboxing a value to rebox it immediately).

Note that this only handles boxing and unboxing conversions occurring through calls to valueOf or one of the intValue, byteValue, etc. methods. Casts that command a conversion are reported by UnnecessaryCast instead.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryBoxingRule

Example(s):

{
        // Instead of
        Integer integer = Integer.valueOf(2);
        // you may just write
        Integer integer = 2;

        int i = integer.intValue(); // similarly for unboxing

        // Instead of
        int x = Integer.valueOf("42");
        // you may just write
        int x = Integer.parseInt("42");
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryBoxing" />

UnnecessaryCast

Since: PMD 6.24.0

Priority: Medium (3)

Minimum Language Version: Java 1.5

Detects casts which could be removed as the operand of the cast is already suitable for the context type. For instance, in the following:

Object context = (Comparable) "o";

The cast is unnecessary. This is because String already is a subtype of both Comparable and Object.

This will also flag casts that can be avoided because of the autoboxing feature of Java 5.

Integer integer = (Integer) 1;

The literal would be autoboxed to Integer anyway.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryCastRule

Example(s):

import java.util.function.Function;
class SomeClass {
   static {
      Object o; long l; int i; Integer boxedInt;

      // reference conversions

      o = (Object) new SomeClass();      // unnecessary
      o = (SomeClass) o;                 // necessary (narrowing cast)
      o = (Comparable<String>) "string"; // unnecessary

      // primitive conversions

      l = (long) 2;   // unnecessary
      l = (long) 2.0; // necessary (narrowing cast)
      l = (byte) i;   // necessary (narrowing cast)

      // boxing/unboxing casts (since java 5)

      o = (Integer) 3;    // unnecessary (autoboxing would apply)
      o = (long) 3;       // necessary (would be boxed to Long)
      l = (int) boxedInt; // necessary (cannot cast Integer to long)

      // casts that give a target type to a lambda/ method ref are necessary

      o = (Function<Integer, String>) Integer::toString; // necessary (no target type)
   }
}
import java.util.*;
class SomeClass {
   static {
       /* Casts involving access to collections were common before Java 5, because collections
        * were not generic. This rule may hence be useful when converting from using a raw
        * type like `List` to a parameterized type like `List<String>`.
        */
       List<String> stringList = Arrays.asList("a", "b");
       String element = (String) stringList.get(0); // this cast is unnecessary
   }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryCast" />

UnnecessaryConstructor

Since: PMD 1.0

Priority: Medium (3)

This rule detects when a constructor is not necessary; i.e., when there is only one constructor and the constructor is identical to the default constructor. The default constructor should has same access modifier as the declaring class. In an enum type, the default constructor is implicitly private.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryConstructorRule

Example(s):

public class Foo {
  public Foo() {}
}

This rule has the following properties:

Name Default Value Description
ignoredAnnotations javax.inject.Inject , com.google.inject.Inject , org.springframework.beans.factory.annotation.Autowired Fully qualified names of the annotation types that should be ignored by this rule

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryConstructor" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UnnecessaryConstructor">
    <properties>
        <property name="ignoredAnnotations" value="javax.inject.Inject,com.google.inject.Inject,org.springframework.beans.factory.annotation.Autowired" />
    </properties>
</rule>

UnnecessaryFullyQualifiedName

Since: PMD 5.0

Priority: Medium Low (4)

Import statements allow the use of non-fully qualified names. The use of a fully qualified name which is covered by an import statement is redundant. Consider using the non-fully qualified name.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryFullyQualifiedNameRule

Example(s):

import java.util.List;

public class Foo {
    private java.util.List list1;   // Unnecessary FQN
    private List list2;             // More appropriate given import of 'java.util.List'
}

This rule has the following properties:

Name Default Value Description
reportStaticMethods true Report unnecessary static method qualifiers like in Collections.emptyList(), if the method is imported or inherited.
reportStaticFields true Report unnecessary static field qualifiers like in Math.PI, if the field is imported or inherited.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName">
    <properties>
        <property name="reportStaticMethods" value="true" />
        <property name="reportStaticFields" value="true" />
    </properties>
</rule>

UnnecessaryImport

Since: PMD 6.34.0

Priority: Medium Low (4)

Reports import statements that can be removed. They are either unused, duplicated, or the members they import are already implicitly in scope, because they’re in java.lang, or the current package.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryImportRule

Example(s):

import java.io.File;            // not used, can be removed
            import java.util.Collections;   // used below
            import java.util.*;             // so this one is not used

            import java.lang.Object;        // imports from java.lang, unnecessary
            import java.lang.Object;        // duplicate, unnecessary

            public class Foo {
                static Object emptyList() {
                    return Collections.emptyList();
                }
            }

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryImport" />

UnnecessaryLocalBeforeReturn

Since: PMD 3.3

Priority: Medium (3)

Avoid the creation of unnecessary local variables

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryLocalBeforeReturnRule

Example(s):

public class Foo {
   public int foo() {
     int x = doSomething();
     return x;  // instead, just 'return doSomething();'
   }
}

This rule has the following properties:

Name Default Value Description
statementOrderMatters true If set to false this rule no longer requires the variable declaration and return statement to be on consecutive lines. Any variable that is used solely in a return statement will be reported.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryLocalBeforeReturn" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UnnecessaryLocalBeforeReturn">
    <properties>
        <property name="statementOrderMatters" value="true" />
    </properties>
</rule>

UnnecessaryModifier

Since: PMD 1.02

Priority: Medium (3)

Fields in interfaces and annotations are automatically public static final, and methods are public abstract. Classes, interfaces or annotations nested in an interface or annotation are automatically public static (all nested interfaces and annotations are automatically static). Nested enums are automatically static. For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryModifierRule

Example(s):

public @interface Annotation {
    public abstract void bar();     // both abstract and public are ignored by the compiler
    public static final int X = 0;  // public, static, and final all ignored
    public static class Bar {}      // public, static ignored
    public static interface Baz {}  // ditto
}
public interface Foo {
    public abstract void bar();     // both abstract and public are ignored by the compiler
    public static final int X = 0;  // public, static, and final all ignored
    public static class Bar {}      // public, static ignored
    public static interface Baz {}  // ditto
}
public class Bar {
    public static interface Baz {}  // static ignored
    public static enum FoorBar {    // static ignored
        FOO;
    }
}
public class FooClass {
    static record BarRecord() {}     // static ignored
}
public interface FooInterface {
    static record BarRecord() {}     // static ignored
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryModifier" />

UnnecessaryReturn

Since: PMD 1.3

Priority: Medium (3)

Avoid the use of unnecessary return statements. A return is unnecessary when no instructions follow anyway.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryReturnRule

Example(s):

public class Foo {
    public void bar() {
        int x = 42;
        return;
    }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UnnecessaryReturn" />

UnnecessarySemicolon

Since: PMD 6.46.0

Priority: Medium (3)

Reports unnecessary semicolons (so called "empty statements" and "empty declarations"). These can be removed without changing the program. The Java grammar allows them for historical reasons, but they should be avoided.

This rule will not report empty statements that are syntactically required, for instance, because they are the body of a control statement.

This rule replaces EmptyStatementNotInLoop.

This rule is defined by the following XPath expression:

(: empty declarations :)
      //EmptyDeclaration
      (: empty statements :)
    | //Block/EmptyStatement

Example(s):

class Foo {
    {
        toString();; // one of these semicolons is unnecessary
        if (true); // this semicolon is not unnecessary, but it could be an empty block instead (not reported)
    }
}; // this semicolon is unnecessary

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UnnecessarySemicolon" />

UseDiamondOperator

Since: PMD 6.11.0

Priority: Medium (3)

Minimum Language Version: Java 1.7

In some cases, explicit type arguments in a constructor call for a generic type may be replaced by diamond type arguments (<>), and be inferred by the compiler. This rule recommends that you use diamond type arguments anywhere possible, since it avoids duplication of the type arguments, and makes the code more concise and readable.

This rule is useful when upgrading a codebase to Java 1.7, Java 1.8, or Java 9. The diamond syntax was first introduced in Java 1.7. In Java 8, improvements in Java’s type inference made more type arguments redundant. In Java 9, type arguments inference was made possible for anonymous class constructors.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UseDiamondOperatorRule

Example(s):

import java.util.*;
            class Foo {
                static {
                    List<String> strings;
                    strings = new ArrayList<String>(); // unnecessary duplication of type parameters
                    strings = new ArrayList<>();       // using diamond type arguments is more concise

                    strings = new ArrayList(); // accidental use of a raw type, you can use ArrayList<> instead

                    strings = new ArrayList<>() {
                        // for anonymous classes, this is possible since Java 9 only
                    };
                }
            }

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UseDiamondOperator" />

UseExplicitTypes

Since: PMD 7.0.0

Priority: Medium (3)

Minimum Language Version: Java 10

Java 10 introduced the var keyword. This reduces the amount of code written because java can infer the type from the initializer of the variable declaration.

This is essentially a trade-off: On the one hand, it can make code more readable by eliminating redundant information. On the other hand, it can make code less readable by eliding useful information. There is no blanket rule for when var should be used or shouldn’t.

It may make sense to use var when the type is inherently clear upon reading the statement (ie: assignment to either a literal value or a constructor call). Those use cases can be enabled through properties.

Notice that lambda parameters are allowed, as they are already inferred by default (the var keyword is completely optional).

See also Local Variable Type Inference Style Guidelines.

This rule is defined by the following XPath expression:

//LocalVariableDeclaration[@TypeInferred = true()]
    [not(VariableDeclarator[*[pmd-java:nodeIs("Literal")]]) or $allowLiterals = false()]
    [not(VariableDeclarator[ConstructorCall]) or $allowCtors = false()]

This rule has the following properties:

Name Default Value Description
allowLiterals false Allow when variables are directly initialized with literals
allowCtors false Allow when variables are directly initialized with a constructor call

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UseExplicitTypes" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UseExplicitTypes">
    <properties>
        <property name="allowLiterals" value="false" />
        <property name="allowCtors" value="false" />
    </properties>
</rule>

UselessParentheses

Since: PMD 5.0

Priority: Medium Low (4)

Parenthesized expressions are used to override the default operator precedence rules. Parentheses whose removal would not change the relative nesting of operators are unnecessary, because they don’t change the semantics of the enclosing expression.

Some parentheses that strictly speaking are unnecessary, may still be considered useful for readability. This rule allows to ignore violations on two kinds of unnecessary parentheses:

  • "Clarifying" parentheses, which separate operators of difference precedence. While unnecessary, they make precedence rules explicit, which may be useful for rarely used operators. For example:
      (a + b) & c // is equivalent to `a + b & c`, but probably clearer
    

    Unset the property ignoreClarifying to report them.

  • "Balancing" parentheses, which are unnecessary but visually balance out another pair of parentheses around an equality operator. For example, those two expressions are equivalent:
      (a == null) != (b == null)
      a == null != (b == null)
    

    The parentheses on the right are required, and the parentheses on the left are just more visually pleasing. Unset the property ignoreBalancing to report them.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule

Example(s):

public class Foo {
    {
        int n = 0;
        n = (n);         // here
        n = (n * 2) * 3; // and here
        n = n * (2 * 3); // and here
    }
}

This rule has the following properties:

Name Default Value Description
ignoreClarifying true Ignore parentheses that separate expressions of difference precedence, like in (a % 2 == 0) ? x : -x
ignoreBalancing true Ignore unnecessary parentheses that appear balanced around an equality operator, because the other operand requires parentheses.For example, in (a == null) == (b == null), only the second pair of parentheses is necessary, but the expression is clearer that way.

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UselessParentheses" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UselessParentheses">
    <properties>
        <property name="ignoreClarifying" value="true" />
        <property name="ignoreBalancing" value="true" />
    </properties>
</rule>

UselessQualifiedThis

Since: PMD 5.4.0

Priority: Medium (3)

Reports qualified this usages in the same class.

This rule is defined by the following XPath expression:

//ThisExpression/ClassType
[ ancestor::*[pmd-java:nodeIs('TypeDeclaration')][1]/@SimpleName = ./@SimpleName ]

Example(s):

public class Foo {
    final Foo otherFoo = Foo.this;  // use "this" directly

    public void doSomething() {
         final Foo anotherFoo = Foo.this;  // use "this" directly
    }

    private ActionListener returnListener() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                doSomethingWithQualifiedThis(Foo.this);  // This is fine
            }
        };
    }

    private class Foo3 {
        final Foo myFoo = Foo.this;  // This is fine
    }

    private class Foo2 {
        final Foo2 myFoo2 = Foo2.this;  // Use "this" direclty
    }
}

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UselessQualifiedThis" />

UseShortArrayInitializer

Since: PMD 6.15.0

Priority: Medium (3)

When declaring and initializing array fields or variables, it is not necessary to explicitly create a new array using new. Instead one can simply define the initial content of the array as a expression in curly braces.

E.g. int[] x = new int[] { 1, 2, 3 }; can be written as int[] x = { 1, 2, 3 };.

This rule is defined by the following XPath expression:

//VariableDeclarator
    [VariableId[@TypeInferred = false() and @ArrayType = true()]]
    [ArrayAllocation/ArrayInitializer]

Example(s):

Foo[] x = new Foo[] { ... }; // Overly verbose
Foo[] x = { ... }; //Equivalent to above line

Use this rule by referencing it:

<rule ref="category/java/codestyle.xml/UseShortArrayInitializer" />

UseUnderscoresInNumericLiterals

Since: PMD 6.10.0

Priority: Medium (3)

Minimum Language Version: Java 1.7

Since Java 1.7, numeric literals can use underscores to separate digits. This rule enforces that numeric literals above a certain length use these underscores to increase readability.

The rule only supports decimal (base 10) literals for now. The acceptable length under which literals are not required to have underscores is configurable via a property. Even under that length, underscores that are misplaced (not making groups of 3 digits) are reported.

This rule is defined by the following XPath expression:

//NumericLiteral
 (: Filter out literals in base other than 10 :)
 [@Base = 10]
 (: Filter out ignored field name :)
 [not(ancestor::VariableDeclarator[1][@Name = 'serialVersionUID'])]
 [
   some $num in tokenize(@Image, "[dDfFlLeE+\-]")
   satisfies not(
                  ( contains($num, ".")
                    and string-length(substring-before($num, ".")) <= $acceptableDecimalLength
                    and string-length(substring-after($num, ".")) <= $acceptableDecimalLength
                    or string-length($num) <= $acceptableDecimalLength
                  )
                  and not(contains($num,"_"))
                  or matches($num, "^[0-9]{1,3}(_[0-9]{3})*(\.([0-9]{3}_)*[0-9]{1,3})?$")
                )
 ]

Example(s):

public class Foo {
    private int num = 1000000; // should be 1_000_000
}

This rule has the following properties:

Name Default Value Description
acceptableDecimalLength 4 Length under which literals in base 10 are not required to have underscores

Use this rule with the default properties by just referencing it:

<rule ref="category/java/codestyle.xml/UseUnderscoresInNumericLiterals" />

Use this rule and customize it:

<rule ref="category/java/codestyle.xml/UseUnderscoresInNumericLiterals">
    <properties>
        <property name="acceptableDecimalLength" value="4" />
    </properties>
</rule>