Table of Contents
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 the constructor’s class often causes th…
- 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: Using constants in interfaces is a bad practice. Interfaces define types, constants are implement…
- 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: Excessive coupling to implementation types (e.g., ‘HashSet’) limits your ability to use alternate…
- 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…
- PreserveStackTrace: Reports exceptions that are thrown from within a catch block, yet don’t refer to the exception pa…
- PrimitiveWrapperInstantiation: Reports usages of primitive wrapper constructors. They are deprecated since Java 9 an…
- 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…
- SimplifiableTestAssertion: Reports test assertions that may be simplified using a more specific assertion method…
- 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 …
- UnnecessaryVarargsArrayCreation: Reports explicit array creation when a varargs is expected. For instance: …
- 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…
- 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. Since PMD 6.50.0 …
- UnusedPrivateMethod: Unused Private Method detects when a private method is declared but is unused.
- UseCollectionIsEmpty: The isEmpty() method on java.util.Collection is provided to determine if a collection has any ele…
- UseEnumCollections: Wherever possible, use ‘EnumSet’ or ‘EnumMap’ instead of ‘HashSet’ and ‘HashMap’ when the keys …
- 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
- 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.
- 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…
- EmptyControlStatement: Reports control statements whose body is empty, as well as empty initializers. The ch…
- 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 …
- FinalParameterInAbstractMethod: Declaring a method parameter as final for an interface method is useless because the implementati…
- ForLoopShouldBeWhileLoop: Some for loops can be simplified to while loops, this makes them more concise.
- 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 …
- LambdaCanBeMethodReference: This rule reports lambda expressions that can be written more succinctly as a method reference. T…
- 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: Reports method and constructor parameters that can be made final because they are never reassigne…
- MethodNamingConventions: Configurable naming conventions for method declarations. This rule reports method dec…
- 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 declaration is deemed to be pr…
- 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, enum constant names or parameter names that are very short are not helpf…
- 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.
- UnnecessaryBoxing: Reports explicit boxing and unboxing conversions that may safely be removed, either b…
- UnnecessaryCast: Detects casts which could be removed as the operand of the cast is already suitable for the conte…
- 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. A return is unnecessary when no instructions foll…
- UnnecessarySemicolon: Reports unnecessary semicolons (so called "empty statements" and "empty declarations"). …
- UseDiamondOperator: In some cases, explicit type arguments in a constructor call for a generic type may be replaced b…
- UseExplicitTypes: Java 10 introduced the ‘var’ keyword. This reduces the amount of code written because java can in…
- UselessParentheses: Parenthesized expressions are used to override the default operator precedence rules….
- 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 …
Design
- AbstractClassWithoutAnyMethod: If an abstract class does not provide any methods, it may be acting as a simple data container th…
- 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: Reports unchecked exceptions in the ‘throws’ clause of a method or constructor. Java doesn’t forc…
- ClassWithOnlyPrivateConstructorsShouldBeFinal: Reports classes that may be made final because they cannot be extended from outside their compila…
- CognitiveComplexity: Methods that are highly complex are difficult to read and more costly to maintain. If you include…
- CollapsibleIfStatements: Reports nested ‘if’ statements that can be merged together by joining their conditions with a boo…
- 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: This rule reports exceptions thrown and caught in an enclosing try statement. This use of excepti…
- ExcessiveImports: A high number of imports can indicate a high degree of coupling within an object. This rule count…
- 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: Reports non-final fields whose value never changes once object initialization ends, and hence may…
- InvalidJavaBean: Identifies beans, that don’t follow the [JavaBeans API specification](https://download.oracle.com…
- LawOfDemeter: The law of Demeter is a simple rule that says "only talk to friends". It forbids fetching data fr…
- 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…
- MutableStaticState: Non-private static fields should be made constants (or immutable references) by declaring them fi…
- NcssCount: This rule uses the NCSS (Non-Commenting Source Statements) metric to determine the number of line…
- 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: Reports ternary expression with the form ‘condition ? literalBoolean : foo’ or ‘condition ? foo :…
- 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: Reports fields which may be converted to a local variable. This is so because in every method whe…
- 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
- 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
- AssignmentInOperand: Avoid assignments in operands; this can make code more complicated and harder to read.
- AssignmentToNonFinalStatic: Identifies a possible unsafe usage of a static field.
- AvoidAccessibilityAlteration: Methods such as ‘getDeclaredConstructors()’, ‘getDeclaredMethods()’, and ‘getDeclaredFields()’ al…
- AvoidAssertAsIdentifier: Use of the term ‘assert’ will conflict with newer versions of Java since it is a reserved word. S…
- AvoidBranchingStatementAsLastInLoop: Using a branching statement as the last part of a loop may be a bug, and/or is confusing. Ensure …
- AvoidCallingFinalize: The method Object.finalize() is called by the garbage collector on an object when garbage collect…
- AvoidCatchingNPE: Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide…
- AvoidCatchingThrowable: Catching Throwable errors is not recommended since its scope is very broad. It includes runtime i…
- AvoidDecimalLiteralsInBigDecimalConstructor: One might assume that the result of "new BigDecimal(0.1)" is exactly equal to 0.1, but it is actu…
- AvoidDuplicateLiterals: Code containing duplicate String literals can usually be improved by declaring the String as a co…
- AvoidEnumAsIdentifier: Use of the term ‘enum’ will conflict with newer versions of Java since it is a reserved word. Sin…
- AvoidFieldNameMatchingMethodName: It can be confusing to have a field name with the same name as a method. While this is permitted,…
- AvoidFieldNameMatchingTypeName: It is somewhat confusing to have a field name matching the declaring type name. This probably mea…
- AvoidInstanceofChecksInCatchClause: Each caught exception type should be handled in its own catch clause.
- AvoidLiteralsInIfCondition: Avoid using hard-coded literals in conditional statements. By declaring them as static variables …
- AvoidLosingExceptionInformation: Statements in a catch block that invoke accessors on the exception without using the information …
- AvoidMultipleUnaryOperators: The use of multiple unary operators may be problematic, and/or confusing. Ensure that the intende…
- AvoidUsingOctalValues: Integer literals should not start with zero since this denotes that the rest of literal will be i…
- BrokenNullCheck: The null check is broken since it will throw a NullPointerException itself. It is likely that you…
- CallSuperFirst: Super should be called at the start of the method
- CallSuperLast: Super should be called at the end of the method
- CheckSkipResult: The skip() method may skip a smaller number of bytes than requested. Check the returned value to …
- ClassCastExceptionWithToArray: When deriving an array of a specific class from your Collection, one should provide an array of t…
- CloneMethodMustBePublic: The java manual says "By convention, classes that implement this interface should override Object…
- CloneMethodMustImplementCloneable: The method clone() should only be implemented if the class implements the Cloneable interface wit…
- CloneMethodReturnTypeMustMatchClassName: If a class implements ‘Cloneable’ the return type of the method ‘clone()’ must be the class name….
- CloseResource: Ensure that resources (like ‘java.sql.Connection’, ‘java.sql.Statement’, and ‘java.sql.ResultSet’…
- CompareObjectsWithEquals: Use ‘equals()’ to compare object references; avoid comparing them with ‘==’. Since comparing obje…
- ComparisonWithNaN: Reports comparisons with double and float ‘NaN’ (Not-a-Number) values. These are [spe…
- ConfusingArgumentToVarargsMethod: Reports a confusing argument passed to a varargs method. This can occur when an array…
- ConstructorCallsOverridableMethod: Reports calls to overridable methods on ‘this’ during object initialization. These are invoked on…
- DetachedTestCase: The method appears to be a test case since it has public or default visibility, non-static access…
- DoNotCallGarbageCollectionExplicitly: Calls to ‘System.gc()’, ‘Runtime.getRuntime().gc()’, and ‘System.runFinalization()’ are not advis…
- DoNotExtendJavaLangThrowable: Extend Exception or RuntimeException instead of Throwable.
- DoNotHardCodeSDCard: Use Environment.getExternalStorageDirectory() instead of "/sdcard"
- DoNotTerminateVM: Web applications should not call ‘System.exit()’, since only the web container or the application…
- DoNotThrowExceptionInFinally: Throwing exceptions within a ‘finally’ block is confusing since they may mask other exceptions or…
- DontImportSun: Avoid importing anything from the ‘sun.’ packages. These packages are not portable and are likely…
- DontUseFloatTypeForLoopIndices: Don’t use floating point for loop indices. If you must use floating point, use double unless you’…
- EmptyCatchBlock: Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circ…
- EmptyFinalizer: Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Obje…
- EqualsNull: Tests for null should not use the equals() method. The ‘==’ operator should be used instead.
- FinalizeDoesNotCallSuperFinalize: If the finalize() is implemented, its last action should be to call super.finalize. Note that Ora…
- FinalizeOnlyCallsSuperFinalize: If the finalize() is implemented, it should do something besides just calling super.finalize(). N…
- FinalizeOverloaded: Methods named finalize() should not have parameters. It is confusing and most likely an attempt …
- FinalizeShouldBeProtected: When overriding the finalize(), the new method should be set as protected. If made public, other…
- IdempotentOperations: Avoid idempotent operations - they have no effect.
- ImplicitSwitchFallThrough: Switch statements without break or return statements for each case option may indicate problemati…
- InstantiationToGetClass: Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
- InvalidLogMessageFormat: Check for messages in slf4j and log4j2 (since 6.19.0) loggers with non matching number of argumen…
- JumbledIncrementer: Avoid jumbled loop incrementers - it’s usually a mistake, and is confusing even if intentional.
- JUnitSpelling: In JUnit 3, the setUp method is used to set up all data entities required in running tests. …
- JUnitStaticSuite: The suite() method in a JUnit test needs to be both public and static.
- MethodWithSameNameAsEnclosingClass: A method should not have the same name as its containing class. This would be confusing as it wou…
- MisplacedNullCheck: The null check here is misplaced. If the variable is null a ‘NullPointerException’ will be thrown…
- MissingSerialVersionUID: Serializable classes should provide a serialVersionUID field. The serialVersionUID field is also …
- MissingStaticMethodInNonInstantiatableClass: A class that has private constructors and does not have any static methods or fields cannot be us…
- MoreThanOneLogger: Normally only one logger is used in each class. This rule supports slf4j, log4j, Java Util Loggin…
- NonCaseLabelInSwitchStatement: A non-case label (e.g. a named break/continue label) was present in a switch statement. This is l…
- NonSerializableClass: If a class is marked as ‘Serializable’, then all fields need to be serializable as well. In order…
- NonStaticInitializer: A non-static initializer block will be called any time a constructor is invoked (just prior to in…
- NullAssignment: Assigning a "null" to a variable (outside of its declaration) is usually bad form. Sometimes, th…
- OverrideBothEqualsAndHashcode: Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or ov…
- ProperCloneImplementation: Object clone() should be implemented with super.clone().
- ProperLogger: A logger should normally be defined private static final and be associated with the correct class…
- ReturnEmptyCollectionRatherThanNull: For any method that returns an collection (such as an array, Collection or Map), it is better to …
- ReturnFromFinallyBlock: Avoid returning from a finally block, this can discard exceptions.
- SimpleDateFormatNeedsLocale: Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-approp…
- SingleMethodSingleton: Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is t…
- SingletonClassReturningNewInstance: A singleton class should only ever have one instance. Failure to check whether an ins…
- StaticEJBFieldShouldBeFinal: According to the J2EE specification, an EJB should not have any static fields with write access. …
- StringBufferInstantiationWithChar: Individual character values provided as initialization arguments will be converted into integers….
- SuspiciousEqualsMethodName: The method name and parameter number are suspiciously close to ‘Object.equals’, which can denote …
- SuspiciousHashcodeMethodName: The method name and return type are suspiciously close to hashCode(), which may denote an intenti…
- SuspiciousOctalEscape: A suspicious octal escape sequence was found inside a String literal. The Java language specifica…
- TestClassWithoutTestCases: Test classes typically end with the suffix "Test", "Tests" or "TestCase". Having a non-test class…
- UnconditionalIfStatement: Do not use "if" statements whose conditionals are always true or always false.
- UnnecessaryBooleanAssertion: A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the…
- UnnecessaryCaseChange: Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
- UnnecessaryConversionTemporary: Avoid the use temporary objects when converting primitives to Strings. Use the static conversion …
- UnusedNullCheckInEquals: After checking an object reference for null, you should invoke equals() on that object rather tha…
- UseCorrectExceptionLogging: To make sure the full stacktrace is printed out, use the logging statement with two arguments: a …
- UseEqualsToCompareStrings: Using ‘==’ or ‘!=’ to compare strings is only reliable if the interned string (‘String#intern()’)…
- UselessOperationOnImmutable: An operation on an Immutable object (String, BigDecimal or BigInteger) won’t change the object it…
- UseLocaleWithCaseConversions: When doing ‘String::toLowerCase()/toUpperCase()’ conversions, use an explicit locale argument to …
- UseProperClassLoader: In J2EE, the getClassLoader() method might not work as expected. Use Thread.currentThread().getCo…
Multithreading
- 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…
- 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
- 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 more efficient ‘Arrays.copyOf’ or ‘S…
- AvoidCalendarDateCreation: Problem: ‘java.util.Calendar’ is a heavyweight object and expensive to create. It should only be …
- 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…
- BigIntegerInstantiation: Don’t create instances of already existing BigInteger (‘BigInteger.ZERO’, ‘BigInteger.ONE’), for …
- 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…
- 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…
- 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 …
- 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://javadoc.io/static/commons-fileupload/commons-fileupload/…
- 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
- 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
-
quickstart (
rulesets/java/quickstart.xml
):Quickstart configuration of PMD. Includes the rules that are most likely to apply everywhere.
It contains the following rules:
AbstractClassWithoutAnyMethod, AssignmentInOperand, AssignmentToNonFinalStatic, AvoidAccessibilityAlteration, AvoidBranchingStatementAsLastInLoop, AvoidCatchingThrowable, AvoidDecimalLiteralsInBigDecimalConstructor, AvoidDollarSigns, AvoidInstanceofChecksInCatchClause, AvoidMessageDigestField, AvoidMultipleUnaryOperators, AvoidProtectedFieldInFinalClass, AvoidProtectedMethodInFinalClassNotExtending, AvoidStringBufferField, AvoidThreadGroup, AvoidUsingHardCodedIP, AvoidUsingOctalValues, AvoidUsingVolatile, BigIntegerInstantiation, BrokenNullCheck, CheckResultSet, CheckSkipResult, ClassCastExceptionWithToArray, ClassNamingConventions, ClassWithOnlyPrivateConstructorsShouldBeFinal, CloneMethodMustBePublic, CloneMethodMustImplementCloneable, CloneMethodReturnTypeMustMatchClassName, CloseResource, CompareObjectsWithEquals, ComparisonWithNaN, ConstantsInInterface, ControlStatementBraces, DefaultLabelNotLastInSwitchStmt, DoNotCallGarbageCollectionExplicitly, DoNotExtendJavaLangError, DoNotExtendJavaLangThrowable, DontCallThreadRun, DontUseFloatTypeForLoopIndices, DoubleBraceInitialization, DoubleCheckedLocking, EmptyCatchBlock, EmptyControlStatement, EmptyFinalizer, EqualsNull, ExtendsObject, FinalFieldCouldBeStatic, FinalParameterInAbstractMethod, ForLoopCanBeForeach, ForLoopShouldBeWhileLoop, FormalParameterNamingConventions, GenericsNaming, GuardLogStatement, IdempotentOperations, IdenticalCatchBranches, ImplicitSwitchFallThrough, InstantiationToGetClass, JumbledIncrementer, LambdaCanBeMethodReference, LiteralsFirstInComparisons, LocalVariableNamingConventions, LogicInversion, LooseCoupling, MethodNamingConventions, MisplacedNullCheck, MissingOverride, MissingStaticMethodInNonInstantiatableClass, NonCaseLabelInSwitchStatement, NonStaticInitializer, NonThreadSafeSingleton, NoPackage, OneDeclarationPerLine, OptimizableToArrayCall, OverrideBothEqualsAndHashcode, PackageCase, PreserveStackTrace, PrimitiveWrapperInstantiation, ProperCloneImplementation, ProperLogger, ReturnEmptyCollectionRatherThanNull, ReturnFromFinallyBlock, SimplifiableTestAssertion, SimplifiedTernary, SimplifyBooleanReturns, SimplifyConditional, SingleMethodSingleton, SingletonClassReturningNewInstance, SingularField, SuspiciousEqualsMethodName, SuspiciousHashcodeMethodName, SuspiciousOctalEscape, SwitchStmtsShouldHaveDefault, UncommentedEmptyConstructor, UncommentedEmptyMethodBody, UnconditionalIfStatement, UnnecessaryAnnotationValueElement, UnnecessaryConstructor, UnnecessaryConversionTemporary, UnnecessaryFullyQualifiedName, UnnecessaryImport, UnnecessaryLocalBeforeReturn, UnnecessaryModifier, UnnecessaryReturn, UnnecessarySemicolon, UnsynchronizedStaticFormatter, UnusedFormalParameter, UnusedLocalVariable, UnusedNullCheckInEquals, UnusedPrivateField, UnusedPrivateMethod, UseCollectionIsEmpty, UseEqualsToCompareStrings, UselessOperationOnImmutable, UselessOverridingMethod, UselessParentheses, UselessQualifiedThis, UseLocaleWithCaseConversions, UseNotifyAllInsteadOfNotify, UseStandardCharsets, UseUtilityClass