Avoid Comparisons Against Long.MAX_VALUE / Long.MIN_VALUE
ID |
java.long_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 Long.MAX_VALUE or Long.MIN_VALUE. Such comparisons are always true or always false for any long value, which indicates a logic error.
Rationale
Long.MAX_VALUE is 263 - 1, the largest possible long. Every long is less than or equal to this value, so x < Long.MAX_VALUE is true for all values except Long.MAX_VALUE itself, and x > Long.MAX_VALUE is always false. The same logic applies symmetrically to Long.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 long except MAX_VALUE itself
if (x < Long.MAX_VALUE) {
process(x);
}
// Bad -- always true for any long except MIN_VALUE itself
if (x > Long.MIN_VALUE) {
process(x);
}
Remediation
Replace the boundary constant with the actual domain limit the code intends to enforce, or use Math.addExact() / Math.multiplyExact() for overflow-safe arithmetic:
// Good -- use a meaningful domain bound
if (x < MAX_ALLOWED_OFFSET) {
process(x);
}
// Good -- use exact methods for overflow detection
try {
long result = Math.addExact(a, b);
} catch (ArithmeticException e) {
// handle overflow
}