Avoid Comparisons Against Integer.MAX_VALUE / Integer.MIN_VALUE

ID

java.int_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 Integer.MAX_VALUE or Integer.MIN_VALUE. Such comparisons are always true or always false for any int value, which indicates a logic error.

Rationale

Integer.MAX_VALUE is 231 - 1, the largest possible int. Every int is less than or equal to this value, so x < Integer.MAX_VALUE is true for all values except Integer.MAX_VALUE itself, and x > Integer.MAX_VALUE is always false. The same logic applies symmetrically to Integer.MIN_VALUE.

These comparisons typically reveal a misunderstanding of the constant’s purpose, an overflow guard that cannot work due to two’s-complement arithmetic, or a copy-paste error.

// Bad -- always true for any int except MAX_VALUE itself
if (x < Integer.MAX_VALUE) {
    process(x);
}

// Bad -- always true for any int except MIN_VALUE itself
if (x > Integer.MIN_VALUE) {
    process(x);
}

Remediation

Replace the boundary constant with the actual domain limit the code intends to enforce, or use long arithmetic when overflow detection is the goal:

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

// Good -- use long arithmetic for overflow detection
long result = (long) a + b;
if (result <= Integer.MAX_VALUE && result >= Integer.MIN_VALUE) {
    return (int) result;
}