Increment Or Decrement On Floating Point

ID

java.increment_on_floating_point

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Java

Tags

code-style, reliability

Description

Reports ++ or --, prefix or postfix, applied to a variable declared float, double, Float or Double.

Rationale

Increment and decrement read intuitively as "the next integer", and most developers expect x++ to behave like it does on int or long. Floating-point precision breaks that expectation: once a value is large enough, adding 1.0 can be too small a change to represent, and the operation does nothing:

for (float x = 16_000_000; x < 17_000_000; x++) {
    // Bug: x stops advancing once 1.0 is no longer representable at this magnitude
}
// This loop never terminates.

The same loop written with int terminates normally, because integer arithmetic has no such precision cliff. The floating-point version compiles cleanly and looks identical to a working loop, so the defect only shows up at runtime, as a hang.

Remediation

Use the compound assignment operator instead; it is exactly as short and states the increment explicitly:

float x = 0f;
double y = 1.0;

x += 1.0;   // Compliant
y -= 1.0;   // Compliant

© 2026 Xygeni. All rights reserved