Avoid Comparing a Value With Itself

ID

java.compare_value_to_itself

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:570, CWE:571, reliability, suspicious-comparison

Description

Reports comparisons where both operands are the same expression, such as x == x, a > a, or this.field != this.field. The result of such a comparison is always constant (true or false), which indicates a copy-paste error or logic mistake.

Rationale

A comparison of an expression with itself always yields a predictable result:

  • x == x is always true (except for NaN)

  • x != x is always false (except for NaN)

  • x > x, x < x are always false

  • x >= x, x <= x are always true

In nearly all cases, the developer intended to compare against a different variable.

// Bad -- always true
if (x == x) {
    process(x);
}

// Bad -- always false
if (count > count) {
    overflow();
}

Remediation

Replace one side of the comparison with the intended variable:

// Good -- compare different values
if (x == y) {
    process(x);
}

if (count > maxCount) {
    overflow();
}