Assignment with Self-Increment
ID |
java.assignment_with_self_increment |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability, suspicious-comparison |
Description
Reports statements of the form i = i++ or i = i-- where the self-assignment with post-increment is a no-op.
Rationale
Post-increment (i++) returns the value of i before incrementing. When that value is immediately assigned back to i, the increment is overwritten:
int i = 0;
i = i++; // i is still 0 -- the increment is lost
int j = 5;
j = j--; // j is still 5 -- the decrement is lost
This is one of the most common Java gotchas. The JVM first saves the old value, then increments, then assigns the saved old value back.
Remediation
Use plain increment or pre-increment:
i++; // Simple post-increment
i = ++i; // Pre-increment (returns the new value)
i = i + 1; // Explicit addition