Avoid Comparisons Against Float.MAX_VALUE / Float.MIN_VALUE

ID

java.float_compare_against_max_min

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability, suspicious-comparison

Description

Reports relational comparisons (<, >, <=, >=) where one operand is Float.MAX_VALUE or Float.MIN_VALUE. Such comparisons are always true or always false for any finite float value, which indicates a logic error.

Rationale

Float.MAX_VALUE is the largest finite float value (~3.4 x 1038). Any finite float is less than or equal to it, so x < Float.MAX_VALUE is almost always true, and x > Float.MAX_VALUE is almost always false. Similarly, Float.MIN_VALUE is the smallest positive non-zero float (~1.4 x 10-45), so comparisons against it are rarely meaningful.

These comparisons typically reveal a misunderstanding of the constant’s purpose or a copy-paste error.

// Bad -- comparison is always true for any normal float
if (x < Float.MAX_VALUE) {
    process(x);
}

// Bad -- comparison is almost always true
if (x > Float.MIN_VALUE) {
    process(x);
}

Remediation

Replace the boundary constant with the actual domain limit the code intends to enforce:

// Good -- use a meaningful domain bound
if (x < MAX_ALLOWED_WEIGHT) {
    process(x);
}

// Good -- explicit zero check when that is the intent
if (x > 0.0f) {
    process(x);
}