Index of all built-in rules available for Java
Edit me

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 a private field / method from another class, the Java compiler will generate a acc…
  • 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.
  • AvoidReassigningLoopVariables: Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables ca…
  • AvoidReassigningParameters: Reassigning values to incoming parameters is not recommended. Use temporary local variables inst…
  • 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…
  • 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: All switch statements should include a default option to catch any unspecified values.
  • SystemPrintln: References to System.(out|err).print are usually intended for debugging purposes and can remain …
  • UnusedFormalParameter: Avoid passing parameters to methods or constructors without actually referencing them in the meth…
  • UnusedImports: Avoid unused import statements to prevent unwanted dependencies. This rule will also find unused …
  • UnusedLocalVariable: Detects when a local variable is declared and/or assigned, but not used.
  • 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…
  • 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: Use explicit scoping instead of accidental usage of default package private level. The rule allow…
  • DontImportJavaLang: Avoid importing anything from the package ‘java.lang’. These classes are automatically imported …
  • DuplicateImports: Duplicate or overlapping import statements should be avoided.
  • 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.
  • 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 …
  • 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…
  • 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…
  • 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.
  • 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(), getDeclaredConstructor(Class[]) and setAccessible(), a…
  • AvoidAssertAsIdentifier: Use of the term ‘assert’ will conflict with newer versions of Java since it is a reserved word.
  • 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.
  • 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 class name. This probably me…
  • 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…
  • BadComparison: Avoid equality comparisons with Double.NaN. Due to the implicit lack of representation precision …
  • BeanMembersShouldSerialize: If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializab…
  • 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. Tha…
  • CloneThrowsCloneNotSupportedException: The method clone() should throw a CloneNotSupportedException.
  • 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 ==.
  • ConstructorCallsOverridableMethod: Calling overridable methods during construction poses a risk of invoking methods on an incomplete…
  • DataflowAnomalyAnalysis: The dataflow analysis tracks local definitions, undefinitions and references to variables on diff…
  • 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 advised. Co…
  • DoNotCallSystemExit: Web applications should not call System.exit(), since only the web container or the application s…
  • DoNotExtendJavaLangThrowable: Extend Exception or RuntimeException instead of Throwable.
  • DoNotHardCodeSDCard: Use Environment.getExternalStorageDirectory() instead of "/sdcard"
  • 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 likel…
  • 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…
  • EmptyFinallyBlock: Empty finally blocks serve no purpose and should be removed.
  • EmptyIfStmt: Empty If Statement finds instances where a condition is checked but nothing is done about it.
  • EmptyInitializer: Empty initializers serve no purpose and should be removed.
  • EmptyStatementBlock: Empty block statements serve no purpose and should be removed.
  • EmptyStatementNotInLoop: An empty statement (or a semicolon by itself) that is not used as the sole body of a ‘for’ or ‘wh…
  • EmptySwitchStatements: Empty switch statements serve no purpose and should be removed.
  • EmptySynchronizedBlock: Empty synchronized blocks serve no purpose and should be removed.
  • EmptyTryBlock: Avoid empty try blocks - what’s the point?
  • EmptyWhileStmt: Empty While Statement finds all instances where a while statement does nothing. If it is a timing…
  • 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.
  • ImportFromSamePackage: There is no need to import a type that lives in the same package.
  • 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 - its 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.
  • LoggerIsNotStaticFinal: Deprecated In most cases, the Logger reference can be declared as static and final. This rule is deprecated …
  • MethodWithSameNameAsEnclosingClass: Non-constructor methods should not have the same name as the enclosing class.
  • MisplacedNullCheck: The null check here is misplaced. If the variable is null a NullPointerException will be thrown. …
  • MissingBreakInSwitch: Switch statements without break or return statements for each case option may indicate problemati…
  • 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 lega…
  • 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…
  • ReturnEmptyArrayRatherThanNull: For any method that returns an array, it is a better to return an empty array rather than a null …
  • 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: Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is t…
  • 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 equals(Object), which can denote a…
  • 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 end with the suffix Test. Having a non-test class with that name is not a good pract…
  • 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 only works if intern version is used on both sides. Use the…
  • 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

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…
  • 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: Java uses the ‘short’ type to reduce memory usage, not to optimize calculation. In fact, the JVM …
  • 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: Since it passes in a literal of length 1, calls to (string).startsWith can be rewritten using (st…
  • 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 a ne…
  • UseIndexOfChar: Use String.indexOf(char) when checking for the index of a single character; it executes faster.
  • 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