Index of all built-in rules available for Java

Best Practices

Rules which enforce generally accepted best practices.
  • AbstractClassWithoutAbstractMethod: The abstract class does not contain any abstract methods. An abstract class suggests an incomplet…
  • AccessorClassGeneration: Instantiation by way of private constructors from outside of the constructor’s class often causes…
  • AccessorMethodGeneration: When accessing private fields / methods from another class, the Java compiler will generate acces…
  • ArrayIsStoredDirectly: Constructors and methods receiving arrays should clone objects and store the copy. This prevents …
  • AvoidMessageDigestField: Declaring a MessageDigest instance as a field make this instance directly available to multiple t…
  • AvoidPrintStackTrace: Avoid printStackTrace(); use a logger call instead.
  • AvoidReassigningCatchVariables: Reassigning exception variables caught in a catch statement should be avoided because of: 1) If i…
  • AvoidReassigningLoopVariables: Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables ca…
  • AvoidReassigningParameters: Reassigning values to incoming parameters of a method or constructor is not recommended, as this …
  • AvoidStringBufferField: StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if…
  • AvoidUsingHardCodedIP: Application with hard-coded IP addresses can become impossible to deploy in some cases. Externali…
  • CheckResultSet: Always check the return values of navigation methods (next, previous, first, last) of a ResultSet…
  • ConstantsInInterface: Avoid constants in interfaces. Interfaces should define types, constants are implementation detai…
  • DefaultLabelNotLastInSwitchStmt: By convention, the default label should be the last label in a switch statement.
  • DoubleBraceInitialization: Double brace initialisation is a pattern to initialise eg collections concisely. But it implicitl…
  • ForLoopCanBeForeach: Reports loops that can be safely replaced with the foreach syntax. The rule considers loops over …
  • ForLoopVariableCount: Having a lot of control variables in a ‘for’ loop makes it harder to see what range of values the…
  • GuardLogStatement: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise sk…
  • JUnit4SuitesShouldUseSuiteAnnotation: In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated thr…
  • JUnit4TestShouldUseAfterAnnotation: In JUnit 3, the tearDown method was used to clean up all data entities required in running tests….
  • JUnit4TestShouldUseBeforeAnnotation: In JUnit 3, the setUp method was used to set up all data entities required in running tests. JUni…
  • JUnit4TestShouldUseTestAnnotation: In JUnit 3, the framework executed all methods which started with the word test as a unit test. I…
  • JUnit5TestShouldBePackagePrivate: Reports JUnit 5 test classes and methods that are not package-private. Contrary to JUnit 4 tests,…
  • JUnitAssertionsShouldIncludeMessage: JUnit assertions should include an informative message - i.e., use the three-argument version of …
  • JUnitTestContainsTooManyAsserts: Unit tests should not contain too many asserts. Many asserts are indicative of a complex test, fo…
  • JUnitTestsShouldIncludeAssert: JUnit tests should include at least one assertion. This makes the tests more robust, and using a…
  • JUnitUseExpected: In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions.
  • LiteralsFirstInComparisons: Position literals first in all String comparisons, if the second argument is null then NullPointe…
  • LooseCoupling: The use of implementation types (i.e., HashSet) as object references limits your ability to use a…
  • MethodReturnsInternalArray: Exposing internal arrays to the caller violates object encapsulation since elements can be remove…
  • MissingOverride: Annotating overridden methods with @Override ensures at compile time that the method …
  • OneDeclarationPerLine: Java allows the use of several variables declaration of the same type on one line. However, it ca…
  • PositionLiteralsFirstInCaseInsensitiveComparisons: Deprecated Position literals first in comparisons, if the second argument is null then NullPointerExceptions…
  • PositionLiteralsFirstInComparisons: Deprecated Position literals first in comparisons, if the second argument is null then NullPointerExceptions…
  • PreserveStackTrace: Throwing a new exception from a catch block without passing the original exception into the new e…
  • ReplaceEnumerationWithIterator: Consider replacing Enumeration usages with the newer java.util.Iterator
  • ReplaceHashtableWithMap: Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required.
  • ReplaceVectorWithList: Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe oper…
  • SwitchStmtsShouldHaveDefault: Switch statements should be exhaustive, to make their control flow easier to follow. …
  • SystemPrintln: References to System.(out|err).print are usually intended for debugging purposes and can remain …
  • UnusedAssignment: Reports assignments to variables that are never used before the variable is overwritten, …
  • UnusedFormalParameter: Reports parameters of methods and constructors that are not referenced them in the method body. P…
  • UnusedImports: Deprecated Reports import statements that are not used within the file. This also reports duplicate imports,…
  • UnusedLocalVariable: Detects when a local variable is declared and/or assigned, but not used. Variables whose name sta…
  • UnusedPrivateField: Detects when a private field is declared and/or assigned a value, but not used.
  • UnusedPrivateMethod: Unused Private Method detects when a private method is declared but is unused.
  • UseAssertEqualsInsteadOfAssertTrue: This rule detects JUnit assertions in object equality. These assertions should be made by more sp…
  • UseAssertNullInsteadOfAssertTrue: This rule detects JUnit assertions in object references equality. These assertions should be made…
  • UseAssertSameInsteadOfAssertTrue: This rule detects JUnit assertions in object references equality. These assertions should be made…
  • UseAssertTrueInsteadOfAssertEquals: When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, ins…
  • UseCollectionIsEmpty: The isEmpty() method on java.util.Collection is provided to determine if a collection has any ele…
  • UseStandardCharsets: Starting with Java 7, StandardCharsets provides constants for common Charset objects, such as UTF…
  • UseTryWithResources: Java 7 introduced the try-with-resources statement. This statement ensures that each resource is …
  • UseVarargs: Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic …
  • WhileLoopWithLiteralBoolean: ‘do {} while (true);’ requires reading the end of the statement before it is apparent that it loo…

Code Style

Rules which enforce a specific coding style.
  • AbstractNaming: Deprecated Abstract classes should be named ‘AbstractXXX’. This rule is deprecated and will be removed with …
  • AtLeastOneConstructor: Each non-static class should declare at least one constructor. Classes with solely static members…
  • AvoidDollarSigns: Avoid using dollar signs in variable/method/class/interface names.
  • AvoidFinalLocalVariable: Deprecated Avoid using final local variables, turn them into fields. Note that this is a controversial rule …
  • AvoidPrefixingMethodParameters: Deprecated Prefixing parameters by ‘in’ or ‘out’ pollutes the name of the parameters and reduces code readab…
  • AvoidProtectedFieldInFinalClass: Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent…
  • AvoidProtectedMethodInFinalClassNotExtending: Do not use protected methods in most final classes since they cannot be subclassed. This should o…
  • AvoidUsingNativeCode: Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portabilit…
  • BooleanGetMethodName: Methods that return boolean results should be named as predicate statements to denote this. I.e, …
  • CallSuperInConstructor: It is a good practice to call super() in a constructor. If super() is not called but another cons…
  • ClassNamingConventions: Configurable naming conventions for type declarations. This rule reports type declara…
  • CommentDefaultAccessModifier: To avoid mistakes if we want that an Annotation, Class, Enum, Method, Constructor or Field have a…
  • ConfusingTernary: Avoid negation within an "if" expression with an "else" clause. For example, rephrase: ‘if (x !=…
  • ControlStatementBraces: Enforce a policy for braces on control statements. It is recommended to use braces on ‘if … els…
  • DefaultPackage: Deprecated Use explicit scoping instead of accidental usage of default package private level. The rule allow…
  • DontImportJavaLang: Deprecated Avoid importing anything from the package ‘java.lang’. These classes are automatically imported …
  • DuplicateImports: Deprecated Duplicate or overlapping import statements should be avoided. This rule is deprecated since PMD 6…
  • EmptyMethodInAbstractClassShouldBeAbstract: Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to …
  • ExtendsObject: No need to explicitly extend Object.
  • FieldDeclarationsShouldBeAtStartOfClass: Fields should be declared at the top of the class, before any method declarations, constructors, …
  • FieldNamingConventions: Configurable naming conventions for field declarations. This rule reports variable declarations …
  • ForLoopShouldBeWhileLoop: Some for loops can be simplified to while loops, this makes them more concise.
  • ForLoopsMustUseBraces: Deprecated Avoid using ‘for’ statements without using curly braces. If the code formatting or indentation is…
  • FormalParameterNamingConventions: Configurable naming conventions for formal parameters of methods and lambdas. This ru…
  • GenericsNaming: Names for references to generic values should be limited to a single uppercase letter.
  • IdenticalCatchBranches: Identical ‘catch’ branches use up vertical space and increase the complexity of code without …
  • IfElseStmtsMustUseBraces: Deprecated Avoid using if..else statements without using surrounding braces. If the code formatting or inden…
  • IfStmtsMustUseBraces: Deprecated Avoid using if statements without using braces to surround the code block. If the code formatting…
  • LinguisticNaming: This rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they …
  • LocalHomeNamingConvention: The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’.
  • LocalInterfaceSessionNamingConvention: The Local Interface of a Session EJB should be suffixed by ‘Local’.
  • LocalVariableCouldBeFinal: A local variable assigned only once can be declared final.
  • LocalVariableNamingConventions: Configurable naming conventions for local variable declarations and other locally-scoped …
  • LongVariable: Fields, formal arguments, or local variable names that are too long can make the code difficult t…
  • MDBAndSessionBeanNamingConvention: The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’.
  • MethodArgumentCouldBeFinal: A method argument that is never re-assigned within the method can be declared final.
  • MethodNamingConventions: Configurable naming conventions for method declarations. This rule reports method dec…
  • MIsLeadingVariableName: Deprecated Detects when a non-field has a name starting with ‘m_’. This usually denotes a field and could b…
  • NoPackage: Detects when a class, interface, enum or annotation does not have a package definition.
  • OnlyOneReturn: A method should have only one exit point, and that should be the last statement in the method.
  • PackageCase: Detects when a package definition contains uppercase characters.
  • PrematureDeclaration: Checks for variables that are defined before they might be used. A reference is deemed to be prem…
  • RemoteInterfaceNamingConvention: Remote Interface of a Session EJB should not have a suffix.
  • RemoteSessionInterfaceNamingConvention: A Remote Home interface type of a Session EJB should be suffixed by ‘Home’.
  • ShortClassName: Short Classnames with fewer than e.g. five characters are not recommended.
  • ShortMethodName: Method names that are very short are not helpful to the reader.
  • ShortVariable: Fields, local variables, or parameter names that are very short are not helpful to the reader.
  • SuspiciousConstantFieldName: Deprecated Field names using all uppercase characters - Sun’s Java naming conventions indicating constants -…
  • TooManyStaticImports: If you overuse the static import feature, it can make your program unreadable and unmaintainable,…
  • UnnecessaryAnnotationValueElement: Avoid the use of value in annotations when it’s the only element.
  • UnnecessaryCast: This rule detects when a cast is unnecessary while accessing collection elements. This rule is mo…
  • UnnecessaryConstructor: This rule detects when a constructor is not necessary; i.e., when there is only one constructor a…
  • UnnecessaryFullyQualifiedName: Import statements allow the use of non-fully qualified names. The use of a fully qualified name …
  • UnnecessaryImport: Reports import statements that can be removed. They are either unused, duplicated, or…
  • UnnecessaryLocalBeforeReturn: Avoid the creation of unnecessary local variables
  • UnnecessaryModifier: Fields in interfaces and annotations are automatically ‘public static final’, and methods are ‘pu…
  • UnnecessaryReturn: Avoid the use of unnecessary return statements.
  • UseDiamondOperator: Use the diamond operator to let the type be inferred automatically. With the Diamond operator it …
  • UselessParentheses: Useless parentheses should be removed.
  • UselessQualifiedThis: Reports qualified this usages in the same class.
  • UseShortArrayInitializer: When declaring and initializing array fields or variables, it is not necessary to explicitly crea…
  • UseUnderscoresInNumericLiterals: Since Java 1.7, numeric literals can use underscores to separate digits. This rule enforces that …
  • VariableNamingConventions: Deprecated A variable naming conventions rule - customize this to your liking. Currently, it checks for fin…
  • WhileLoopsMustUseBraces: Deprecated Avoid using ‘while’ statements without using braces to surround the code block. If the code forma…

Design

Rules that help you discover design issues.
  • AbstractClassWithoutAnyMethod: If an abstract class does not provides any methods, it may be acting as a simple data container t…
  • AvoidCatchingGenericException: Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in tr…
  • AvoidDeeplyNestedIfStmts: Avoid creating deeply nested if-then statements since they are harder to read and error-prone to …
  • AvoidRethrowingException: Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
  • AvoidThrowingNewInstanceOfSameException: Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same typ…
  • AvoidThrowingNullPointerException: Avoid throwing NullPointerExceptions manually. These are confusing because most people will assum…
  • AvoidThrowingRawExceptionTypes: Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exce…
  • AvoidUncheckedExceptionsInSignatures: A method or constructor should not explicitly declare unchecked exceptions in its ‘throws’ clause…
  • ClassWithOnlyPrivateConstructorsShouldBeFinal: A class with only private constructors should be final, unless the private constructor is invoked…
  • CognitiveComplexity: Methods that are highly complex are difficult to read and more costly to maintain. If you include…
  • CollapsibleIfStatements: Sometimes two consecutive ‘if’ statements can be consolidated by separating their conditions with…
  • CouplingBetweenObjects: This rule counts the number of unique attributes, local variables, and return types within an obj…
  • CyclomaticComplexity: The complexity of methods directly affects maintenance costs and readability. Concentrating too m…
  • DataClass: Data Classes are simple data holders, which reveal most of their state, and without complex funct…
  • DoNotExtendJavaLangError: Errors are system exceptions. Do not extend them.
  • ExceptionAsFlowControl: Using Exceptions as form of flow control is not recommended as they obscure true exceptions when …
  • ExcessiveClassLength: Excessive class file lengths are usually indications that the class may be burdened with excessiv…
  • ExcessiveImports: A high number of imports can indicate a high degree of coupling within an object. This rule count…
  • ExcessiveMethodLength: When methods are excessively long this usually indicates that the method is doing more than its n…
  • ExcessiveParameterList: Methods with numerous parameters are a challenge to maintain, especially if most of them share th…
  • ExcessivePublicCount: Classes with large numbers of public methods and attributes require disproportionate testing effo…
  • FinalFieldCouldBeStatic: If a final field is assigned to a compile-time constant, it could be made static, thus saving ove…
  • GodClass: The God Class rule detects the God Class design flaw using metrics. God classes do too many thing…
  • ImmutableField: Identifies private fields whose values never change once object initialization ends either in the…
  • LawOfDemeter: The Law of Demeter is a simple rule, that says "only talk to friends". It helps to reduce couplin…
  • LogicInversion: Use opposite operator instead of negating the whole expression with a logic complement operator.
  • LoosePackageCoupling: Avoid using classes from the configured package hierarchy outside of the package hierarchy, excep…
  • ModifiedCyclomaticComplexity: Deprecated Complexity directly affects maintenance costs is determined by the number of decision points in a…
  • MutableStaticState: Non-private static fields should be made constants (or immutable references) by declaring them fi…
  • NcssConstructorCount: Deprecated This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of l…
  • NcssCount: This rule uses the NCSS (Non-Commenting Source Statements) metric to determine the number of line…
  • NcssMethodCount: Deprecated This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of l…
  • NcssTypeCount: Deprecated This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of l…
  • NPathComplexity: The NPath complexity of a method is the number of acyclic execution paths through that method. Wh…
  • SignatureDeclareThrowsException: A method/constructor shouldn’t explicitly throw the generic java.lang.Exception, since it is uncl…
  • SimplifiedTernary: Look for ternary operators with the form ‘condition ? literalBoolean : foo’ or ‘condition ? foo :…
  • SimplifyBooleanAssertion: Avoid negation in an assertTrue or assertFalse test. For example, rephrase: assertTrue(!expr)…
  • SimplifyBooleanExpressions: Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability.
  • SimplifyBooleanReturns: Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditional…
  • SimplifyConditional: No need to check for null before an instanceof; the instanceof keyword returns false when given a…
  • SingularField: Fields whose scopes are limited to just single methods do not rely on the containing object to pr…
  • StdCyclomaticComplexity: Deprecated Complexity directly affects maintenance costs is determined by the number of decision points in a…
  • SwitchDensity: A high ratio of statements to labels in a switch statement implies that the switch statement is o…
  • TooManyFields: Classes that have too many fields can become unwieldy and could be redesigned to have fewer field…
  • TooManyMethods: A class with too many methods is probably a good suspect for refactoring, in order to reduce its …
  • UselessOverridingMethod: The overriding method merely calls the same method defined in a superclass.
  • UseObjectForClearerAPI: When you write a public method, you should be thinking in terms of an API. If your method is publ…
  • UseUtilityClass: For classes that only have static methods, consider making them utility classes. Note that this d…

Documentation

Rules that are related to code documentation.
  • CommentContent: A rule for the politically correct… we don’t want to offend anyone.
  • CommentRequired: Denotes whether javadoc (formal) comments are required (or unwanted) for specific language elements.
  • CommentSize: Determines whether the dimensions of non-header comments found are within the specified limits.
  • UncommentedEmptyConstructor: Uncommented Empty Constructor finds instances where a constructor does not contain statements, bu…
  • UncommentedEmptyMethodBody: Uncommented Empty Method Body finds instances where a method body does not contain statements, bu…

Error Prone

Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.

Multithreading

Rules that flag issues when dealing with multiple threads of execution.
  • AvoidSynchronizedAtMethodLevel: Method-level synchronization can cause problems when new code is added to the method. Block-level…
  • AvoidThreadGroup: Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment i…
  • AvoidUsingVolatile: Use of the keyword ‘volatile’ is generally used to fine tune a Java application, and therefore, r…
  • DoNotUseThreads: The J2EE specification explicitly forbids the use of threads. Threads are resources, that should …
  • DontCallThreadRun: Explicitly calling Thread.run() method will execute in the caller’s thread of control. Instead, …
  • DoubleCheckedLocking: Partially created objects can be returned by the Double Checked Locking pattern when used in Java…
  • NonThreadSafeSingleton: Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possib…
  • UnsynchronizedStaticDateFormatter: Deprecated SimpleDateFormat instances are not synchronized. Sun recommends using separate format instances f…
  • UnsynchronizedStaticFormatter: Instances of ‘java.text.Format’ are generally not synchronized. Sun recommends using separate for…
  • UseConcurrentHashMap: Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can p…
  • UseNotifyAllInsteadOfNotify: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, th…

Performance

Rules that flag suboptimal code.
  • AddEmptyString: The conversion of literals to strings by concatenating them with empty strings is inefficient. It…
  • AppendCharacterWithChar: Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.
  • AvoidArrayLoops: Instead of manually copying data between two arrays, use the efficient Arrays.copyOf or System.ar…
  • AvoidCalendarDateCreation: Problem: A Calendar is a heavyweight object and expensive to create. Solution: Use ‘new Date()’, …
  • AvoidFileStream: The FileInputStream and FileOutputStream classes contains a finalizer method which will cause gar…
  • AvoidInstantiatingObjectsInLoops: New objects created within loops should be checked to see if they can created outside them and re…
  • AvoidUsingShortType: Deprecated Note: this rule is deprecated, as its rationale does not hold. Java uses the ‘short’ type to redu…
  • BigIntegerInstantiation: Don’t create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for J…
  • BooleanInstantiation: Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boole…
  • ByteInstantiation: Calling new Byte() causes memory allocation that can be avoided by the static Byte.valueOf(). It …
  • ConsecutiveAppendsShouldReuse: Consecutive calls to StringBuffer/StringBuilder .append should be chained, reusing the target obj…
  • ConsecutiveLiteralAppends: Consecutively calling StringBuffer/StringBuilder.append(…) with literals should be avoided. Sin…
  • InefficientEmptyStringCheck: String.trim().length() == 0 (or String.trim().isEmpty() for the same reason) is an inefficient wa…
  • InefficientStringBuffering: Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buf…
  • InsufficientStringBufferDeclaration: Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many times…
  • IntegerInstantiation: Calling new Integer() causes memory allocation that can be avoided by the static Integer.valueOf(…
  • LongInstantiation: Calling new Long() causes memory allocation that can be avoided by the static Long.valueOf(). It …
  • OptimizableToArrayCall: Calls to a collection’s ‘toArray(E[])’ method should specify a target array of zero size. This al…
  • RedundantFieldInitializer: Java will initialize fields with known default values so any explicit initialization of those sam…
  • ShortInstantiation: Calling new Short() causes memory allocation that can be avoided by the static Short.valueOf(). I…
  • SimplifyStartsWith: Deprecated Note: this rule is deprecated for removal, as the optimization is insignificant. Calls to ‘string…
  • StringInstantiation: Avoid instantiating String objects; this is usually unnecessary since they are immutable and can …
  • StringToString: Avoid calling toString() on objects already known to be string instances; this is unnecessary.
  • TooFewBranchesForASwitchStatement: Switch statements are intended to be used to support complex branching behaviour. Using a switch …
  • UnnecessaryWrapperObjectCreation: Most wrapper classes provide static conversion methods that avoid the need to create intermediate…
  • UseArrayListInsteadOfVector: ArrayList is a much better Collection implementation than Vector if thread-safe operation is not …
  • UseArraysAsList: The ‘java.util.Arrays’ class has a ‘asList()’ method that should be used when you want to create …
  • UseIndexOfChar: Use String.indexOf(char) when checking for the index of a single character; it executes faster.
  • UseIOStreamsWithApacheCommonsFileItem: Problem: Use of [FileItem.get()](https://commons.apache.org/proper/commons-fileupload/apidocs/org…
  • UselessStringValueOf: No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
  • UseStringBufferForStringAppends: The use of the ‘+=’ operator for appending strings causes the JVM to create and use an internal S…
  • UseStringBufferLength: Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toStrin…

Security

Rules that flag potential security flaws.
  • HardCodedCryptoKey: Do not use hard coded values for cryptographic operations. Please store keys outside of source code.
  • InsecureCryptoIv: Do not use hard coded initialization vector in cryptographic operations. Please use a randomly ge…

Additional rulesets