##### Overview

- Download PMD 3.9
- What's new in PMD 3.9
- PMD in the news
- PMD-related products and books
- Best practices
- Future directions
- Similar projects
- Credits
- License
- What does 'PMD' mean?

##### Usage

- Installation
- Command line usage
- Ant task usage
- Maven plugin usage
- IDE plugin usage
- Suppressing warnings
- Finding duplicated code
- JSP support

##### Customizing PMD

- Compiling PMD
- How to write a rule
- Writing XPath rules
- How to make a rule set
- How it works

##### For example

- Run PMD on a Sourceforge project

##### Rule Sets

- Index
- Basic
- Braces
- Code Size
- Clone
- Controversial
- Coupling
- Design
- Finalizers
- Import Statements
- J2EE
- Javabeans
- JUnit Tests
- Logging (Java)
- Logging (Jakarta)
- Migrating
- Naming
- Optimizations
- Strict Exceptions
- Strings
- Sun Security
- Unused Code
- Java Server Pages
- Java Server Faces

##### Project Documentation

- About PMD
- Project Info
- Project Reports
- Development Process

## Basic Rules

The Basic Ruleset contains a collection of good practices which everyone should follow.

### EmptyCatchBlock

Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported.

This rule is defined by the following XPath expression:

    //CatchStatement
     [count(Block/BlockStatement) = 0 and ($allowCommentedBlocks != 'true' or Block/@containsComment = 'false')]
     [FormalParameter/Type/ReferenceType
       /ClassOrInterfaceType[@Image != 'InterruptedException' and @Image != 'CloneNotSupportedException']
     ]

Here's an example of code that would trigger this rule:

    public void doSomething() {
      try {
        FileInputStream fis = new FileInputStream("/tmp/bugger");
      } catch (IOException ioe) {
          // not good
      }
    }

This rule has the following properties:

Name | Default value | Description
allowCommentedBlocks |  | Empty blocks containing comments will be skipped

### EmptyIfStmt

Empty If Statement finds instances where a condition is checked but nothing is done about it.

This rule is defined by the following XPath expression:

    //IfStatement/Statement
     [EmptyStatement or Block[count(*) = 0]]

Here's an example of code that would trigger this rule:

    public class Foo {
     void bar(int x) {
      if (x == 0) {
       // empty!
      }
     }
    }

### EmptyWhileStmt

Empty While Statement finds all instances where a while statement does nothing. If it is a timing loop, then you should use Thread.sleep() for it; if it's a while loop that does a lot in the exit expression, rewrite it to make it clearer.

This rule is defined by the following XPath expression:

    //WhileStatement/Statement[./Block[count(*) = 0]  or ./EmptyStatement]

Here's an example of code that would trigger this rule:

    public class Foo {
     void bar(int a, int b) {
      while (a == b) {
       // empty!
      }
     }
    }

### EmptyTryBlock

Avoid empty try blocks - what's the point?

This rule is defined by the following XPath expression:

    //TryStatement/Block[1][count(*) = 0]

Here's an example of code that would trigger this rule:

    public class Foo {
     public void bar() {
      try {
      } catch (Exception e) {
        e.printStackTrace();
      }
     }
    }

### EmptyFinallyBlock

Avoid empty finally blocks - these can be deleted.

This rule is defined by the following XPath expression:

    //FinallyStatement[count(Block/BlockStatement) = 0]

Here's an example of code that would trigger this rule:

    public class Foo {
     public void bar() {
      try {
        int x=2;
       } finally {
        // empty!
       }
     }
    }

### EmptySwitchStatements

Avoid empty switch statements.

This rule is defined by the following XPath expression:

    //SwitchStatement[count(*) = 1]

Here's an example of code that would trigger this rule:

    public class Foo {
     public void bar() {
      int x = 2;
      switch (x) {
       // once there was code here
       // but it's been commented out or something
      }
     }
    }

### JumbledIncrementer

Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's intended.

This rule is defined by the following XPath expression:

    //ForStatement
     [
      ForUpdate/StatementExpressionList/StatementExpression/PostfixExpression/PrimaryExpression/PrimaryPrefix/Name/@Image
      =
      ancestor::ForStatement/ForInit//VariableDeclaratorId/@Image
     ]

Here's an example of code that would trigger this rule:

    public class JumbledIncrementerRule1 {
      public void foo() {
       for (int i = 0; i &lt; 10; i++) {
        for (int k = 0; k &lt; 20; i++) {
         System.out.println("Hello");
        }
       }
      }
     }

### ForLoopShouldBeWhileLoop

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

This rule is defined by the following XPath expression:

    //ForStatement
     [count(*) &gt; 1]
     [not(ForInit)]
     [not(ForUpdate)]
     [not(Type and Expression and Statement)]

Here's an example of code that would trigger this rule:

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

### UnnecessaryConversionTemporary

Avoid unnecessary temporaries when converting primitives to Strings

This rule is defined by the following Java class: net.sourceforge.pmd.rules.UnnecessaryConversionTemporary

Here's an example of code that would trigger this rule:

    public String convert(int x) {
      // this wastes an object
      String foo = new Integer(x).toString();
      // this is better
      return Integer.toString(x);
    }

### OverrideBothEqualsAndHashcode

Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.

This rule is defined by the following Java class: net.sourceforge.pmd.rules.OverrideBothEqualsAndHashcode

Here's an example of code that would trigger this rule:

    // this is bad
    public class Bar {
      public boolean equals(Object o) {
          // do some comparison
      }
    }

    // and so is this
    public class Baz {
      public int hashCode() {
          // return some hash value
      }
    }

    // this is OK
    public class Foo {
      public boolean equals(Object other) {
          // do some comparison
      }
      public int hashCode() {
          // return some hash value
      }
    }

### DoubleCheckedLocking

Partially created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing JRE may assign a reference to the baz variable before it creates the object the reference is intended to point to. For more details see http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.

This rule is defined by the following Java class: net.sourceforge.pmd.rules.DoubleCheckedLocking

Here's an example of code that would trigger this rule:

    public class Foo {
      Object baz;
      Object bar() {
        if(baz == null) { //baz may be non-null yet not fully created
          synchronized(this){
            if(baz == null){
              baz = new Object();
            }
          }
        }
        return baz;
      }
    }

### ReturnFromFinallyBlock

Avoid returning from a finally block - this can discard exceptions.

This rule is defined by the following XPath expression:

    //FinallyStatement//ReturnStatement

Here's an example of code that would trigger this rule:

    public class Bar {
     public String foo() {
      try {
       throw new Exception( "My Exception" );
      } catch (Exception e) {
       throw e;
      } finally {
       return "A. O. K."; // Very bad.
      }
     }
    }

### EmptySynchronizedBlock

Avoid empty synchronized blocks - they're useless.

This rule is defined by the following XPath expression:

    //SynchronizedStatement/Block[1][count(*) = 0]

Here's an example of code that would trigger this rule:

    public class Foo {
     public void bar() {
      synchronized (this) {
       // empty!
      }
     }
    }

### UnnecessaryReturn

Avoid unnecessary return statements

This rule is defined by the following Java class: net.sourceforge.pmd.rules.basic.UnnecessaryReturn

Here's an example of code that would trigger this rule:

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

### EmptyStaticInitializer

An empty static initializer was found.

This rule is defined by the following XPath expression:

    //Initializer[@Static='true']/Block[count(*)=0]

Here's an example of code that would trigger this rule:

    public class Foo {
     static {
      // empty
     }
     }

### UnconditionalIfStatement

Do not use "if" statements that are always true or always false.

This rule is defined by the following XPath expression:

    //IfStatement/Expression
     [count(PrimaryExpression)=1]
     /PrimaryExpression/PrimaryPrefix/Literal/BooleanLiteral

Here's an example of code that would trigger this rule:

    public class Foo {
     public void close() {
      if (true) {
           // ...
       }
     }
    }

### EmptyStatementNotInLoop

An empty statement (aka a semicolon by itself) that is not used as the sole body of a for loop or while loop is probably a bug. It could also be a double semicolon, which is useless and should be removed.

This rule is defined by the following XPath expression:

    //EmptyStatement
     [not(
           ../../../ForStatement
           or ../../../WhileStatement
           or ../../../BlockStatement/ClassOrInterfaceDeclaration
           or ../../../../../../ForStatement/Statement[1]
            /Block[1]/BlockStatement[1]/Statement/EmptyStatement
           or ../../../../../../WhileStatement/Statement[1]
            /Block[1]/BlockStatement[1]/Statement/EmptyStatement)
     ]

Here's an example of code that would trigger this rule:

    public class MyClass {
       public void doit() {
          // this is probably not what you meant to do
          ;
          // the extra semicolon here this is not necessary
          System.out.println("look at the extra semicolon");;
       }
    }

### BooleanInstantiation

Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead.

This rule is defined by the following Java class: net.sourceforge.pmd.rules.basic.BooleanInstantiation

Here's an example of code that would trigger this rule:

    public class Foo {
     Boolean bar = new Boolean("true"); // just do a Boolean bar = Boolean.TRUE;
     Boolean buz = Boolean.valueOf(false); // just do a Boolean buz = Boolean.FALSE;
    }

### UnnecessaryFinalModifier

When a class has the final modifier, all the methods are automatically final.

This rule is defined by the following XPath expression:

    //ClassOrInterfaceDeclaration[@Final='true' and @Interface='false']
    /ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration[@Final='true']

Here's an example of code that would trigger this rule:

    public final class Foo {
        // This final modifier is not necessary, since the class is final
        // and thus, all methods are final
        private final void foo() {
        }
    }

### CollapsibleIfStatements

Sometimes two 'if' statements can be consolidated by separating their conditions with a boolean short-circuit operator.

This rule is defined by the following XPath expression:

    //IfStatement[@Else='false']/Statement
     /IfStatement[@Else='false']
     |
    //IfStatement[@Else='false']/Statement
     /Block[count(BlockStatement)=1]/BlockStatement
      /Statement/IfStatement[@Else='false']

Here's an example of code that would trigger this rule:

    public class Foo {
     void bar() {
      if (x) {
       if (y) {
        // do stuff
       }
      }
     }
    }

### UselessOverridingMethod

The overriding method merely calls the same method defined in a superclass

This rule is defined by the following Java class: net.sourceforge.pmd.rules.UselessOverridingMethod

Here's an example of code that would trigger this rule:

    public void foo(String bar) {
        super.foo(bar);      //Why bother overriding?
    }

### ClassCastExceptionWithToArray

if you need to get an array of a class from your Collection, you should pass an array of the desidered class as the parameter of the toArray method. Otherwise you will get a ClassCastException.

This rule is defined by the following XPath expression:

    //CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image !=
    "Object"]]//PrimaryExpression
    [
     PrimaryPrefix/Name[ends-with(@Image, '.toArray')]
     and
     PrimarySuffix/Arguments[count(*) = 0]
    ]

Here's an example of code that would trigger this rule:

    import java.util.ArrayList;
    import java.util.Collection;

    public class Test {

        public static void main(String[] args) {
            Collection c=new ArrayList();
            Integer obj=new Integer(1);
            c.add(obj);

            // this would trigger the rule (and throw a ClassCastException
    if executed)
            Integer[] a=(Integer [])c.toArray();

            // this wouldn't trigger the rule
            Integer[] b=(Integer [])c.toArray(new Integer[c.size()]);
        }
    }

### AvoidDecimalLiteralsInBigDecimalConstructor

One might assume that "new BigDecimal(.1)" is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances notwithstanding. The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal(".1")' is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

This rule is defined by the following XPath expression:

    //AllocationExpression[ClassOrInterfaceType[@Image="BigDecimal"]
    and
    ./Arguments/ArgumentList
    /Expression/PrimaryExpression/PrimaryPrefix/Literal[(not
    (ends-with
    (@Image,'"'))) and contains(@Image,".")]]

Here's an example of code that would trigger this rule:

    import java.math.BigDecimal;
    public class Test {

        public static void main(String[] args) {
          // this would trigger the rule
         BigDecimal bd=new BigDecimal(1.123);
          // this wouldn't trigger the rule
         BigDecimal bd=new BigDecimal("1.123");
          // this wouldn't trigger the rule
         BigDecimal bd=new BigDecimal(12);
        }
    }

### UselessOperationOnImmutable

An operation on an Immutable object (BigDecimal or BigInteger) won't change the object itself. The result of the operation is a new object. Therefore, ignoring the operation result is an error.

This rule is defined by the following Java class: net.sourceforge.pmd.rules.UselessOperationOnImmutable

Here's an example of code that would trigger this rule:

    import java.math.*;
    class Test {
     void method1() {
      BigDecimal bd=new BigDecimal(10);
      bd.add(new BigDecimal(5)); // this will trigger the rule
     }
     void method2() {
      BigDecimal bd=new BigDecimal(10);
      bd = bd.add(new BigDecimal(5)); // this won't trigger the rule
     }
    }

### MisplacedNullCheck

The null check here is misplaced. if the variable is null you'll get a NullPointerException. Either the check is useless (the variable will never be "null") or it's incorrect.

This rule is defined by the following XPath expression:

    //Expression
        /*[self::ConditionalOrExpression or self::ConditionalAndExpression]
         /descendant::PrimaryExpression/PrimaryPrefix
          /Name[starts-with(@Image,
          concat(ancestor::PrimaryExpression/following-sibling::EqualityExpression
           [./PrimaryExpression/PrimaryPrefix/Literal/NullLiteral]
         /PrimaryExpression/PrimaryPrefix
          /Name[count(../../PrimarySuffix)=0]/@Image,"."))
        ]

Here's an example of code that would trigger this rule:

    public class Foo {
     void bar() {
      if (a.equals(baz) &amp;&amp; a != null) {}
     }
    }

### UnusedNullCheckInEquals

After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object's equals() method.

This rule is defined by the following XPath expression:

    //PrimarySuffix[@Image='equals' and not(../PrimaryPrefix/Literal)]
     /../PrimarySuffix/Arguments/ArgumentList/Expression
     /PrimaryExpression/PrimaryPrefix
     /Name[@Image = ./../../../../../../../../../../Expression/ConditionalAndExpression
     /EqualityExpression[@Image="!=" and count(./preceding-sibling::*)=0 and
     ./PrimaryExpression/PrimaryPrefix/Literal/NullLiteral]
      /PrimaryExpression/PrimaryPrefix/Name/@Image]

Here's an example of code that would trigger this rule:

    public class Test {

    public String method1() { return "ok";}
    public String method2() { return null;}

    public void method(String a) {
    String b;
    /*
    I don't know it method1() can be "null"
    but I know "a" is not null..
    I'd better write a.equals(method1())
    */
    if (a!=null &amp;&amp; method1().equals(a)) { // will
    trigger the rule
    //whatever
    }

    if (method1().equals(a) &amp;&amp; a != null) { //
    won't trigger the rule
    //whatever
    }

    if (a!=null &amp;&amp; method1().equals(b)) { // won't
    trigger the rule
    //whatever
    }

    if (a!=null &amp;&amp; "LITERAL".equals(a)) { // won't
    trigger the rule
    //whatever
    }

    if (a!=null &amp;&amp; !a.equals("go")) { // won't
    trigger the rule
    a=method2();
    if (method1().equals(a)) {
    //whatever
    }
    }
    }
    }

### AvoidThreadGroup

Avoid using ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread safe.

This rule is defined by the following XPath expression:

    //AllocationExpression/ClassOrInterfaceType[contains(@Image,'ThreadGroup')] |
    //PrimarySuffix[contains(@Image, 'getThreadGroup')]

Here's an example of code that would trigger this rule:

        public class Bar {
         void buz() {
          ThreadGroup tg = new ThreadGroup("My threadgroup") ;
          tg = new ThreadGroup(tg, "my thread group");
          tg = Thread.currentThread().getThreadGroup();
          tg = System.getSecurityManager().getThreadGroup();
         }
        }

### BrokenNullCheck

The null check is broken since it will throw a Nullpointer itself. The reason is that a method is called on the object when it is null. It is likely that you used || instead of && or vice versa.

This rule is defined by the following XPath expression:

    //IfStatement/Expression[.//NullLiteral]
    [
    .//ConditionalOrExpression/EqualityExpression[@Image='!=']
    [starts-with(../*[position()&gt;1]//PrimaryPrefix/Name/@Image,
    concat(PrimaryExpression//PrimaryPrefix/Name/@Image, '.'))]
    or
    .//ConditionalAndExpression/EqualityExpression[@Image='==']
    [starts-with(../*[position()&gt;1]//PrimaryPrefix/Name/@Image,
    concat(PrimaryExpression//PrimaryPrefix/Name/@Image, '.'))]
    ]

Here's an example of code that would trigger this rule:

    class Foo {
     String munge(String string) {
      // should be &amp;&amp;
      if (string!=null || !string.equals(""))
        return string;
      // should be ||
      if (string==null &amp;&amp; string.equals(""))
        return string;
     }
    }

### BigIntegerInstantiation

Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for 1.5 on, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN)

This rule is defined by the following Java class: net.sourceforge.pmd.rules.basic.BigIntegerInstantiation

Here's an example of code that would trigger this rule:

    public class Test {

     public static void main(String[] args) {
       BigInteger bi=new BigInteger(1);
       BigInteger bi2=new BigInteger("0");
       BigInteger bi3=new BigInteger(0.0);
       BigInteger bi4;
       bi4=new BigInteger(0);
     }
    }

### AvoidUsingOctalValues

Integer literals should not start with zero. Zero means that the rest of literal will be interpreted as an octal value.

This rule is defined by the following Java class: net.sourceforge.pmd.rules.basic.AvoidUsingOctalValues

Here's an example of code that would trigger this rule:

    public class Foo {
      int i = 012; // set i with 10 not 12
      int j = 010; // set j with 8 not 10
      k = i * j; // set k with 80 not 120
    }