Avoid Comparisons Against Byte.MAX_VALUE / Byte.MIN_VALUE

ID

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

Rationale

Byte.MAX_VALUE is 127 and Byte.MIN_VALUE is -128. Since a byte variable is always in the range [-128, 127], comparisons like x < Byte.MAX_VALUE or x >= Byte.MIN_VALUE are tautologically true (or false), making the conditional branch misleading or dead. This usually reveals a misunderstanding of the constant’s purpose or a copy-paste error.

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

// Bad -- comparison is always true
if (x >= Byte.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) {
    process(x);
}

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