• Release notes
  • Getting help
  • Installation and basic CLI usage
  • Making rulesets
  • Configuring rules
  • Best practices
  • Suppressing warnings
  • PMD CLI reference
  • Writing a rule
  • Writing XPath rules
  • Defining rule properties
  • Using and defining code metrics
  • Rule guidelines
  • Testing your rules
  • Copy-paste detection
  • Maven PMD plugin
  • CI integrations
  • Other Tools / Integrations
  • Best Practices

Error Prone

  • Performance
  • Documentation
  • Multithreading
  • JSP Support
  • Java code metrics
  • Apex code metrics
  • Developer resources
  • Building PMD from source
  • Contributing
  • Writing documentation
  • How PMD works
  • Adding a new language
  • Adding a new CPD language
  • Adding metrics support to a language
  • PMD in the press
  • Products & books related to PMD
  • Similar projects
  • What does 'PMD' mean?
  • Old release notes
  • Release process
  • Merging pull requests

Collapse All | Expand All

AssignmentInOperand

Since: PMD 1.03

Priority: Medium (3)

Avoid assignments in operands; this can make code more complicated and harder to read.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentInOperandRule

Example(s):

This rule has the following properties:

Use this rule by referencing it:

AssignmentToNonFinalStatic

Since: PMD 2.2

Identifies a possible unsafe usage of a static field.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentToNonFinalStaticRule

AvoidAccessibilityAlteration

Since: PMD 4.1

Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation.

This rule is defined by the following XPath expression:

AvoidAssertAsIdentifier

Since: PMD 3.4

Priority: Medium High (2)

Use of the term ‘assert’ will conflict with newer versions of Java since it is a reserved word.

AvoidBranchingStatementAsLastInLoop

Since: PMD 5.0

Using a branching statement as the last part of a loop may be a bug, and/or is confusing. Ensure that the usage is not a bug, or consider using another approach.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidBranchingStatementAsLastInLoopRule

AvoidCallingFinalize

Since: PMD 3.0

The method Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It should not be invoked by application logic.

Note that Oracle has declared Object.finalize() as deprecated since JDK 9.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidCallingFinalizeRule

AvoidCatchingNPE

Since: PMD 1.8

Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the original error, causing other, more subtle problems later on.

AvoidCatchingThrowable

Since: PMD 1.2

Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidCatchingThrowableRule

AvoidDecimalLiteralsInBigDecimalConstructor

One might assume that the result of “new BigDecimal(0.1)” is exactly equal to 0.1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

The (String) constructor, on the other hand, is perfectly predictable: ‘new BigDecimal(“0.1”)’ is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

AvoidDuplicateLiterals

Since: PMD 1.0

Code containing duplicate String literals can usually be improved by declaring the String as a constant field.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidDuplicateLiteralsRule

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, having information (field) and actions (method) is not clear naming. Developers versed in Smalltalk often prefer this approach as the methods denote accessor methods.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidFieldNameMatchingMethodNameRule

AvoidFieldNameMatchingTypeName

It is somewhat confusing to have a field name matching the declaring class name. This probably means that type and/or field names should be chosen more carefully.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidFieldNameMatchingTypeNameRule

AvoidInstanceofChecksInCatchClause

Each caught exception type should be handled in its own catch clause.

AvoidLiteralsInIfCondition

Since: PMD 4.2.6

Avoid using hard-coded literals in conditional statements. By declaring them as static variables or private members with descriptive names maintainability is enhanced. By default, the literals “-1” and “0” are ignored. More exceptions can be defined with the property “ignoreMagicNumbers”.

AvoidLosingExceptionInformation

Statements in a catch block that invoke accessors on the exception without using the information only add to code size. Either remove the invocation, or use the return result.

AvoidMultipleUnaryOperators

Since: PMD 4.2

The use of multiple unary operators may be problematic, and/or confusing. Ensure that the intended usage is not a bug, or consider simplifying the expression.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidMultipleUnaryOperatorsRule

AvoidUsingOctalValues

Since: PMD 3.9

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

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AvoidUsingOctalValuesRule

BadComparison

Avoid equality comparisons with Double.NaN. Due to the implicit lack of representation precision when comparing floating point numbers these are likely to cause logic errors.

BeanMembersShouldSerialize

Since: PMD 1.1

If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as transient, static, or have accessor methods in the class. Marking variables as transient is the safest and easiest modification. Accessor methods should follow the Java naming conventions, i.e. for a variable named foo, getFoo() and setFoo() accessor methods should be provided.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.BeanMembersShouldSerializeRule

BrokenNullCheck

Since: PMD 3.8

The null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of && or vice versa.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.BrokenNullCheckRule

CallSuperFirst

Since: PMD 4.2.5

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 find out if it was the case or not.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.CheckSkipResultRule

ClassCastExceptionWithToArray

When deriving an array of a specific class from your Collection, one should provide an array of the same class as the parameter of the toArray() method. Doing otherwise you will will result in a ClassCastException.

CloneMethodMustBePublic

Since: PMD 5.4.0

The java Manual says “By convention, classes that implement this interface should override Object.clone (which is protected) with a public method.”

CloneMethodMustImplementCloneable

Since: PMD 1.9

The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.

The rule can also detect, if the class implements or extends a Cloneable class.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.CloneMethodMustImplementCloneableRule

CloneMethodReturnTypeMustMatchClassName

Minimum Language Version: Java 1.5

If a class implements cloneable the return type of the method clone() must be the class name. That way, the caller of the clone method doesn’t need to cast the returned clone to the correct type.

Note: This is only possible with Java 1.5 or higher.

CloneThrowsCloneNotSupportedException

The method clone() should throw a CloneNotSupportedException.

CloseResource

Since: PMD 1.2.2

Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.CloseResourceRule

CompareObjectsWithEquals

Since: PMD 3.2

Use equals() to compare object references; avoid comparing them with ==.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.CompareObjectsWithEqualsRule

ConstructorCallsOverridableMethod

Since: PMD 1.04

Priority: High (1)

Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.ConstructorCallsOverridableMethodRule

DataflowAnomalyAnalysis

Priority: Low (5)

The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow. From those informations there can be found various problems.

  • UR - Anomaly: There is a reference to a variable that was not defined before. This is a bug and leads to an error.
  • DU - Anomaly: A recently defined variable is undefined. These anomalies may appear in normal source text.
  • DD - Anomaly: A recently defined variable is redefined. This is ominous but don’t have to be a bug.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.DataflowAnomalyAnalysisRule

DoNotCallGarbageCollectionExplicitly

Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not. Moreover, “modern” jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself.

DoNotCallSystemExit

Web applications should not call System.exit(), since only the web container or the application server should stop the JVM. This rule also checks for the equivalent call Runtime.getRuntime().exit().

DoNotExtendJavaLangThrowable

Since: PMD 6.0.0

Extend Exception or RuntimeException instead of Throwable.

DoNotHardCodeSDCard

Use Environment.getExternalStorageDirectory() instead of “/sdcard”

DoNotThrowExceptionInFinally

Priority: Medium Low (4)

Throwing exceptions within a ‘finally’ block is confusing since they may mask other exceptions or code defects. Note: This is a PMD implementation of the Lint4j rule “A throw in a finally block”

DontImportSun

Since: PMD 1.5

Avoid importing anything from the ‘sun.*’ packages. These packages are not portable and are likely to change.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.DontImportSunRule

DontUseFloatTypeForLoopIndices

Since: PMD 4.3

Don’t use floating point for loop indices. If you must use floating point, use double unless you’re certain that float provides enough precision and you have a compelling performance need (space or time).

EmptyCatchBlock

Since: PMD 0.1

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

EmptyFinalizer

Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Object.finalize() as deprecated since JDK 9.

EmptyFinallyBlock

Since: PMD 0.4

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 ‘while’ loop is probably a bug. It could also be a double semicolon, which has no purpose and should be removed.

EmptySwitchStatements

Empty switch statements serve no purpose and should be removed.

EmptySynchronizedBlock

Since: PMD 1.3

Empty synchronized blocks serve no purpose and should be removed.

EmptyTryBlock

Avoid empty try blocks - what’s the point?

EmptyWhileStmt

Since: PMD 0.2

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

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 Oracle has declared Object.finalize() as deprecated since JDK 9.

FinalizeOnlyCallsSuperFinalize

If the finalize() is implemented, it should do something besides just calling super.finalize(). Note that Oracle has declared Object.finalize() as deprecated since JDK 9.

FinalizeOverloaded

Methods named finalize() should not have parameters. It is confusing and most likely an attempt to overload Object.finalize(). It will not be called by the VM.

FinalizeShouldBeProtected

When overriding the finalize(), the new method should be set as protected. If made public, other classes may invoke it at inappropriate times.

IdempotentOperations

Since: PMD 2.0

Avoid idempotent operations - they have no effect.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.IdempotentOperationsRule

ImportFromSamePackage

Since: PMD 1.02

There is no need to import a type that lives in the same package.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.ImportFromSamePackageRule

InstantiationToGetClass

Avoid instantiating an object just to call getClass() on it; use the .class public member instead.

InvalidSlf4jMessageFormat

Since: PMD 5.5.0

Check for messages in slf4j loggers with non matching number of arguments and placeholders.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.InvalidSlf4jMessageFormatRule

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.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.MethodWithSameNameAsEnclosingClassRule

MisplacedNullCheck

Since: PMD 3.5

The null check here is misplaced. If the variable is null a NullPointerException will be thrown. Either the check is useless (the variable will never be “null”) or it is incorrect.

MissingBreakInSwitch

Switch statements without break or return statements for each case option may indicate problematic behaviour. Empty cases are ignored as these indicate an intentional fall-through.

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.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.MoreThanOneLoggerRule

NonCaseLabelInSwitchStatement

A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels.

NonStaticInitializer

A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing.

NullAssignment

Assigning a “null” to a variable (outside of its declaration) is usually bad form. Sometimes, this type of assignment is an indication that the programmer doesn’t completely understand what is going on in the code.

NOTE: This sort of assignment may used in some cases to dereference objects and encourage garbage collection.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.NullAssignmentRule

OverrideBothEqualsAndHashcode

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

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.OverrideBothEqualsAndHashcodeRule

ProperCloneImplementation

Since: PMD 1.4

Object clone() should be implemented with super.clone().

ProperLogger

Since: PMD 3.3

A logger should normally be defined private static final and be associated with the correct class. Private final Log log; is also allowed for rare cases where loggers need to be passed around, with the restriction that the logger needs to be passed into the constructor.

ReturnEmptyArrayRatherThanNull

For any method that returns an array, it is a better to return an empty array rather than a null reference. This removes the need for null checking all results and avoids inadvertent NullPointerExceptions.

ReturnFromFinallyBlock

Since: PMD 1.05

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-appropriate formatting is used.

SingleMethodSingleton

Since: PMD 5.4

Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is that the instance created using the overloaded method is not cached and so, for each call and new objects will be created for every invocation.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.SingleMethodSingletonRule

SingletonClassReturningNewInstance

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.SingletonClassReturningNewInstanceRule

StaticEJBFieldShouldBeFinal

According to the J2EE specification, an EJB should not have any static fields with write access. However, static read-only fields are allowed. This ensures proper behavior especially when instances are distributed by the container on several JREs.

StringBufferInstantiationWithChar

Individual character values provided as initialization arguments will be converted into integers. This can lead to internal buffer sizes that are larger than expected. Some examples:

SuspiciousEqualsMethodName

The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to override the equals(Object) method.

SuspiciousHashcodeMethodName

The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.SuspiciousHashcodeMethodNameRule

SuspiciousOctalEscape

A suspicious octal escape sequence was found inside a String literal. The Java language specification (section 3.10.6) says an octal escape sequence inside a literal String shall consist of a backslash followed by:

Any octal escape sequence followed by non-octal digits can be confusing, e.g. “\038” is interpreted as the octal escape sequence “\03” followed by the literal character “8”.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.SuspiciousOctalEscapeRule

TestClassWithoutTestCases

Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case. Test classes have test methods named testXXX.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.TestClassWithoutTestCasesRule

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 same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false). If you just want a test to halt after finding an error, use the fail() method and provide an indication message of why it did.

UnnecessaryCaseChange

Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.UnnecessaryCaseChangeRule

UnnecessaryConversionTemporary

Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods on the wrapper classes instead.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.UnnecessaryConversionTemporaryRule

UnusedNullCheckInEquals

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

UseCorrectExceptionLogging

To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable.

UseEqualsToCompareStrings

Using ‘==’ or ‘!=’ to compare strings only works if intern version is used on both sides. Use the equals() method instead.

UselessOperationOnImmutable

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

This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.UselessOperationOnImmutableRule

UseLocaleWithCaseConversions

When doing String.toLowerCase()/toUpperCase() conversions, use Locales to avoids problems with languages that have unusual conventions, i.e. Turkish.

UseProperClassLoader

Since: PMD 3.7

In J2EE, the getClassLoader() method might not work as expected. Use Thread.currentThread().getContextClassLoader() instead.

This content cannot be displayed without JavaScript. Please enable JavaScript and reload the page.

  • Quality Clouds Documentation
  • Rules and rulesets

Avoid assignments in operands

Manageability

Assignments in operands make code more complicated and harder to read. Also it can be a signal of a poorly-defined equality operator (assignment operator ‘ = ’ was used instead of the equality operator ‘ == ’."") which will produce unwanted results.

Remediation

This is sometime indicative of the bug where the assignment operator ‘=’ was used instead of the equality operator ‘ == ’.""

Time to fix

See the PMD documentation article:  AssignmentInOperand .

What's here

Related content.

PMD - Lightning rules

IMAGES

  1. Java operators with examples

    avoid assignments in operands java

  2. Operators in Java and its Types

    avoid assignments in operands java

  3. Operators in Java

    avoid assignments in operands java

  4. What are Operators in Java and its Types?

    avoid assignments in operands java

  5. Java Beginners Tutorials #13 Operators and Precedence in Java

    avoid assignments in operands java

  6. Java operators with examples

    avoid assignments in operands java

VIDEO

  1. Questions of Operator Precedence in Java

  2. LOGICAL EXPRESSIONS IN JAVA

  3. 🔔 Top 5 mistakes with Java Sets!

  4. NPTEL PROGRAMMING IN JAVA WEEK 4 ASSIGNMENT 4 ANSWERS FEB 2024| IIT KHARAGPUR

  5. Core

  6. 19 final keyword in java

COMMENTS

  1. while loop

    PMD ships with a lot of rules and the idea is that you select those that you want to use in your own code. If you think, that assignments in operands are OK, simply suppress the warning: @SuppressWarnings("PMD.AssignementInOperand") By the way, this is defined in the controversial ruleset anyway. I wouldn't activate that at all.

  2. Error Prone

    Edit me AssignmentInOperand. Since: PMD 1.03 Priority: Medium (3) Avoid assignments in operands; this can make code more complicated and harder to read. This rule is defined by the following Java class: net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentInOperandRule

  3. Avoid assignments in operands

    Impact. Assignments in operands make code more complicated and harder to read. Also it can be a signal of a poorly-defined equality operator (assignment operator ‘ = ’ was used instead of the equality operator ‘ == ’."") which will produce unwanted results.