Best Practices
- AbstractClassWithoutAbstractMethod: The abstract class does not contain any abstract methods. An abstract class suggestsan incomplete…
- 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 f…
- AvoidPrintStackTrace: Avoid printStackTrace(); use a logger call instead.
- 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 leaksif …
- AvoidUsingHardCodedIP: Application with hard-coded IP addresses can become impossible to deploy in some cases.Externaliz…
- 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.
- ForLoopCanBeForeach: Reports loops that can be safely replaced with the foreach syntax. The rule considers loops overl…
- GuardLogStatement: Whenever using a log level, one should check if the loglevel is actually enabled, orotherwise ski…
- JUnit4SuitesShouldUseSuiteAnnotation: In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicatedthro…
- 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: JUnit tests should not contain too many asserts. Many asserts are indicative of a complex test, …
- 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.
- 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 r…
- OneDeclarationPerLine: Java allows the use of several variables declaration of the same type on one line. However, itcan…
- PositionLiteralsFirstInCaseInsensitiveComparisons: Position literals first in comparisons, if the second argument is null then NullPointerExceptions…
- PositionLiteralsFirstInComparisons: 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 thenew ex…
- 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 o…
- 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…
- UseVarargs: Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic…
Code Style
- AbstractNaming: Deprecated Abstract classes should be named ‘AbstractXXX’.
- AtLeastOneConstructor: Each class should declare at least one constructor.
- AvoidDollarSigns: Avoid using dollar signs in variable/method/class/interface names.
- AvoidFinalLocalVariable: Avoid using final local variables, turn them into fields.
- AvoidPrefixingMethodParameters: 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 shouldon…
- 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 butanother const…
- ClassNamingConventions: Configurable naming conventions for type declarations. This rule reports type declarat…
- CommentDefaultAccessModifier: To avoid mistakes if we want that a Method, Constructor, Field or Nested class have a default acc…
- 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 allows…
- 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, …
- 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…
- GenericsNaming: Names for references to generic values should be limited to a single uppercase letter.
- 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…
- 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.
- 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 decl…
- MIsLeadingVariableName: Detects when a non-field has a name starting with ‘m_’. This usually denotes a field and could b…
- NoPackage: Detects when a class or interface 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: 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 namew…
- 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.
- UselessParentheses: Useless parentheses should be removed.
- UselessQualifiedThis: Look for qualified this usages in the same class.
- VariableNamingConventions: A variable naming conventions rule - customize this to your liking. Currently, itchecks for fina…
- WhileLoopsMustUseBraces: Deprecated Avoid using ‘while’ statements without using braces to surround the code block. If the code forma…
Design
- AbstractClassWithoutAnyMethod: If an abstract class does not provides any methods, it may be acting as a simple data containerth…
- 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,Excep…
- ClassWithOnlyPrivateConstructorsShouldBeFinal: A class with only private constructors should be final, unless the private constructoris 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, andwithout complex functi…
- 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 itsna…
- 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 they are initialized either in the decla…
- 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.Whi…
- SignatureDeclareThrowsException: A method/constructor shouldn’t explicitly throw the generic java.lang.Exception, since itis uncle…
- 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);a…
- 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 ofthe 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 containingobject to pro…
- 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 statementis ov…
- 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 itsc…
- 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 do…
Documentation
- CommentContent: A rule for the politically correct… we don’t want to offend anyone.
- CommentRequired: Denotes whether 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 notcontain statements, but…
- UncommentedEmptyMethodBody: Uncommented Empty Method Body finds instances where a method body does not containstatements, but…
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(), getDeclaredConstructor(Class[]) and setAccessible(),as…
- 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 t…
- 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 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 variableso…
- AvoidLosingExceptionInformation: Statements in a catch block that invoke accessors on the exception without using the informationo…
- AvoidMultipleUnaryOperators: The use of multiple unary operators may be problematic, and/or confusing.Ensure that the intended…
- AvoidUsingOctalValues: Integer literals should not start with zero since this denotes that the rest of literal will bein…
- BadComparison: Avoid equality comparisons with Double.NaN. Due to the implicit lack of representationprecision w…
- 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 ofth…
- CloneMethodMustBePublic: The java Manual says “By convention, classes that implement this interface should overrideObject….
- 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 Connection, Statement, and ResultSet objects) are always closed after…
- 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…
- 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 theapplication se…
- 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 doubleunless you’r…
- EmptyCatchBlock: Empty Catch Block finds instances where an exception is caught, but nothing is done. In most cir…
- 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 timin…
- 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.
- InvalidSlf4jMessageFormat: Check for messages in slf4j loggers with non matching number of arguments and placeholders.
- JumbledIncrementer: Avoid jumbled loop incrementers - its usually a mistake, and is confusing even if intentional.
- JUnitSpelling: Some JUnit framework methods are easy to misspell.
- JUnitStaticSuite: The suite() method in a JUnit test needs to be both public and static.
- LoggerIsNotStaticFinal: In most cases, the Logger reference can be declared as static and final.
- 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.E…
- MissingBreakInSwitch: Switch statements without break or return statements for each case optionmay indicate problematic…
- MissingSerialVersionUID: Serializable classes should provide a serialVersionUID field.
- MissingStaticMethodInNonInstantiatableClass: A class that has private constructors and does not have any static methods or fields cannot be used.
- MoreThanOneLogger: Normally only one logger is used in each class.
- NonCaseLabelInSwitchStatement: A non-case label (e.g. a named break/continue label) was present in a switch statement.This legal…
- NonStaticInitializer: A non-static initializer block will be called any time a constructor is invoked (just prior toinv…
- 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 anull r…
- 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 methodsis th…
- SingletonClassReturningNewInstance: Some classes contain overloaded getInstance. The problem with overloaded getInstance methodsis th…
- StaticEJBFieldShouldBeFinal: According to the J2EE specification, an EJB should not have any static fieldswith write access. H…
- 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 specificat…
- 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 Locales to avoids problems with la…
- 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 environmentit…
- 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.
- 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. Eliminatestatic singletons if possibl…
- UnsynchronizedStaticDateFormatter: SimpleDateFormat instances are not synchronized. Sun recommends using separate format instancesfo…
- UseConcurrentHashMap: Since Java5 brought a new implementation of the Map designed for multi-threaded access, you canpe…
- 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 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) andfor Ja…
- 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 m…
- 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.Sinc…
- InefficientEmptyStringCheck: String.trim().length() is an inefficient way to check if a String is really empty, as itcreates a…
- 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 m…
- 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().It…
- 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
- InsecureCryptoIv: Do not use hard coded initialization vector in cryptographic operations. Please use a randomly ge…
Additional rulesets
-
Android (
rulesets/java/android.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
-
Basic (
rulesets/java/basic.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AvoidBranchingStatementAsLastInLoop, AvoidDecimalLiteralsInBigDecimalConstructor, AvoidMultipleUnaryOperators, AvoidThreadGroup, AvoidUsingHardCodedIP, AvoidUsingOctalValues, BigIntegerInstantiation, BooleanInstantiation, BrokenNullCheck, CheckResultSet, CheckSkipResult, ClassCastExceptionWithToArray, CollapsibleIfStatements, DontCallThreadRun, DontUseFloatTypeForLoopIndices, DoubleCheckedLocking, ExtendsObject, ForLoopShouldBeWhileLoop, JumbledIncrementer, MisplacedNullCheck, OverrideBothEqualsAndHashcode, ReturnFromFinallyBlock, SimplifiedTernary, UnconditionalIfStatement
-
Braces (
rulesets/java/braces.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
ForLoopsMustUseBraces, IfElseStmtsMustUseBraces, IfStmtsMustUseBraces, WhileLoopsMustUseBraces
-
Clone Implementation (
rulesets/java/clone.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
CloneMethodMustBePublic, CloneMethodMustImplementCloneable, CloneMethodReturnTypeMustMatchClassName, CloneThrowsCloneNotSupportedException, ProperCloneImplementation
-
Code Size (
rulesets/java/codesize.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
CyclomaticComplexity, ExcessiveClassLength, ExcessiveMethodLength, ExcessiveParameterList, ExcessivePublicCount, ModifiedCyclomaticComplexity, NcssConstructorCount, NcssCount, NcssMethodCount, NcssTypeCount, NPathComplexity, StdCyclomaticComplexity, TooManyFields, TooManyMethods
-
Comments (
rulesets/java/comments.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
CommentContent, CommentDefaultAccessModifier, CommentRequired, CommentSize
-
Controversial (
rulesets/java/controversial.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AssignmentInOperand, AtLeastOneConstructor, AvoidAccessibilityAlteration, AvoidFinalLocalVariable, AvoidLiteralsInIfCondition, AvoidPrefixingMethodParameters, AvoidUsingNativeCode, AvoidUsingShortType, AvoidUsingVolatile, CallSuperInConstructor, DataflowAnomalyAnalysis, DefaultPackage, DoNotCallGarbageCollectionExplicitly, DontImportSun, NullAssignment, OneDeclarationPerLine, OnlyOneReturn, SuspiciousOctalEscape, UnnecessaryConstructor, UnnecessaryParentheses, UseConcurrentHashMap, UseObjectForClearerAPI
-
Coupling (
rulesets/java/coupling.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
CouplingBetweenObjects, ExcessiveImports, LawOfDemeter, LooseCoupling, LoosePackageCoupling
-
Design (
rulesets/java/design.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AbstractClassWithoutAbstractMethod, AbstractClassWithoutAnyMethod, AccessorClassGeneration, AccessorMethodGeneration, AssignmentToNonFinalStatic, AvoidDeeplyNestedIfStmts, AvoidInstanceofChecksInCatchClause, AvoidProtectedFieldInFinalClass, AvoidProtectedMethodInFinalClassNotExtending, AvoidReassigningParameters, AvoidSynchronizedAtMethodLevel, BadComparison, ClassWithOnlyPrivateConstructorsShouldBeFinal, CloseResource, CompareObjectsWithEquals, ConfusingTernary, ConstantsInInterface, ConstructorCallsOverridableMethod, DataClass, DefaultLabelNotLastInSwitchStmt, EmptyMethodInAbstractClassShouldBeAbstract, EqualsNull, FieldDeclarationsShouldBeAtStartOfClass, FinalFieldCouldBeStatic, GodClass, IdempotentOperations, ImmutableField, InstantiationToGetClass, LogicInversion, MissingBreakInSwitch, MissingStaticMethodInNonInstantiatableClass, NonCaseLabelInSwitchStatement, NonStaticInitializer, NonThreadSafeSingleton, OptimizableToArrayCall, PositionLiteralsFirstInCaseInsensitiveComparisons, PositionLiteralsFirstInComparisons, PreserveStackTrace, ReturnEmptyArrayRatherThanNull, SimpleDateFormatNeedsLocale, SimplifyBooleanExpressions, SimplifyBooleanReturns, SimplifyConditional, SingleMethodSingleton, SingletonClassReturningNewInstance, SingularField, SwitchDensity, SwitchStmtsShouldHaveDefault, TooFewBranchesForASwitchStatement, UncommentedEmptyConstructor, UncommentedEmptyMethodBody, UnnecessaryLocalBeforeReturn, UnsynchronizedStaticDateFormatter, UseCollectionIsEmpty, UseLocaleWithCaseConversions, UseNotifyAllInsteadOfNotify, UseUtilityClass, UseVarargs
-
Empty Code (
rulesets/java/empty.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
EmptyCatchBlock, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptyStaticInitializer, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt
-
Finalizer (
rulesets/java/finalizers.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AvoidCallingFinalize, EmptyFinalizer, FinalizeDoesNotCallSuperFinalize, FinalizeOnlyCallsSuperFinalize, FinalizeOverloaded, FinalizeShouldBeProtected
-
Import Statements (
rulesets/java/imports.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
DontImportJavaLang, DuplicateImports, ImportFromSamePackage, TooManyStaticImports, UnnecessaryFullyQualifiedName, UnusedImports
-
J2EE (
rulesets/java/j2ee.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
DoNotCallSystemExit, DoNotUseThreads, LocalHomeNamingConvention, LocalInterfaceSessionNamingConvention, MDBAndSessionBeanNamingConvention, RemoteInterfaceNamingConvention, RemoteSessionInterfaceNamingConvention, StaticEJBFieldShouldBeFinal, UseProperClassLoader
-
JavaBeans (
rulesets/java/javabeans.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
-
JUnit (
rulesets/java/junit.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
JUnitAssertionsShouldIncludeMessage, JUnitSpelling, JUnitStaticSuite, JUnitTestContainsTooManyAsserts, JUnitTestsShouldIncludeAssert, SimplifyBooleanAssertion, TestClassWithoutTestCases, UnnecessaryBooleanAssertion, UseAssertEqualsInsteadOfAssertTrue, UseAssertNullInsteadOfAssertTrue, UseAssertSameInsteadOfAssertTrue, UseAssertTrueInsteadOfAssertEquals
-
Metrics (
rulesets/java/metrics.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
-
MigratingToJUnit4 (
rulesets/java/migrating_to_junit4.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
JUnit4SuitesShouldUseSuiteAnnotation, JUnit4TestShouldUseAfterAnnotation, JUnit4TestShouldUseBeforeAnnotation, JUnit4TestShouldUseTestAnnotation, JUnitUseExpected
-
Migration (
rulesets/java/migrating.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AvoidAssertAsIdentifier, AvoidEnumAsIdentifier, ByteInstantiation, ForLoopCanBeForeach, IntegerInstantiation, JUnit4SuitesShouldUseSuiteAnnotation, JUnit4TestShouldUseAfterAnnotation, JUnit4TestShouldUseBeforeAnnotation, JUnit4TestShouldUseTestAnnotation, JUnitUseExpected, LongInstantiation, ReplaceEnumerationWithIterator, ReplaceHashtableWithMap, ReplaceVectorWithList, ShortInstantiation
-
Migration13 (
rulesets/java/migrating_to_13.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
ReplaceEnumerationWithIterator, ReplaceHashtableWithMap, ReplaceVectorWithList
-
Migration14 (
rulesets/java/migrating_to_14.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
-
Migration15 (
rulesets/java/migrating_to_15.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AvoidEnumAsIdentifier, ByteInstantiation, IntegerInstantiation, LongInstantiation, ShortInstantiation
-
Naming (
rulesets/java/naming.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AbstractNaming, AvoidDollarSigns, AvoidFieldNameMatchingMethodName, AvoidFieldNameMatchingTypeName, BooleanGetMethodName, ClassNamingConventions, GenericsNaming, LongVariable, MethodNamingConventions, MethodWithSameNameAsEnclosingClass, MisleadingVariableName, MIsLeadingVariableName, NoPackage, PackageCase, ShortClassName, ShortMethodName, ShortVariable, SuspiciousConstantFieldName, SuspiciousEqualsMethodName, SuspiciousHashcodeMethodName, VariableNamingConventions
-
Optimization (
rulesets/java/optimizations.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AddEmptyString, AvoidArrayLoops, AvoidInstantiatingObjectsInLoops, LocalVariableCouldBeFinal, MethodArgumentCouldBeFinal, PrematureDeclaration, RedundantFieldInitializer, SimplifyStartsWith, UnnecessaryWrapperObjectCreation, UseArrayListInsteadOfVector, UseArraysAsList, UseStringBufferForStringAppends
-
Security Code Guidelines (
rulesets/java/sunsecure.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
-
Strict Exceptions (
rulesets/java/strictexception.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AvoidCatchingGenericException, AvoidCatchingNPE, AvoidCatchingThrowable, AvoidLosingExceptionInformation, AvoidRethrowingException, AvoidThrowingNewInstanceOfSameException, AvoidThrowingNullPointerException, AvoidThrowingRawExceptionTypes, DoNotExtendJavaLangError, DoNotThrowExceptionInFinally, ExceptionAsFlowControl, SignatureDeclareThrowsException
-
String and StringBuffer (
rulesets/java/strings.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
AppendCharacterWithChar, AvoidDuplicateLiterals, AvoidStringBufferField, ConsecutiveAppendsShouldReuse, ConsecutiveLiteralAppends, InefficientEmptyStringCheck, InefficientStringBuffering, InsufficientStringBufferDeclaration, StringBufferInstantiationWithChar, StringInstantiation, StringToString, UnnecessaryCaseChange, UseEqualsToCompareStrings, UseIndexOfChar, UselessStringValueOf, UseStringBufferLength
-
Type Resolution (
rulesets/java/typeresolution.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
CloneMethodMustImplementCloneable, LooseCoupling, SignatureDeclareThrowsException, UnusedImports
-
Unnecessary (
rulesets/java/unnecessary.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
UnnecessaryConversionTemporary, UnnecessaryFinalModifier, UnnecessaryModifier, UnnecessaryReturn, UnusedNullCheckInEquals, UselessOperationOnImmutable, UselessOverridingMethod, UselessParentheses, UselessQualifiedThis
-
Unused Code (
rulesets/java/unusedcode.xml
):Deprecated This ruleset is for backwards compatibility.
It contains the following rules:
UnusedFormalParameter, UnusedLocalVariable, UnusedPrivateField, UnusedPrivateMethod