Assignment in Conditional Expression

ID

java.assign_in_condition

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:481, reliability, suspicious-comparison

Description

Reports assignment expressions (=) found inside if or while conditions.

Rationale

Using = instead of == in a conditional is one of the most common programming mistakes. Even when the assignment is intentional, mixing a side effect into the condition expression makes the code harder to review and more likely to be misread as a comparison.

// Bad - likely meant == instead of =
if (b = true) {
    doSomething();
}

Remediation

Replace the assignment with a comparison, or move the assignment to a separate statement before the condition:

// Good - comparison
if (b == true) {
    doSomething();
}

// Good - assignment separated from condition
int x = readNext();
while (x > 0) {
    process(x);
    x = readNext();
}