Avoid Comparisons Against Short.MAX_VALUE / Short.MIN_VALUE

ID

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

Rationale

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

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

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

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

Remediation

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

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

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