This is an issue when comparing a numeric variable with a limited value range against a constant that falls outside the variable’s possible value
range, resulting in a comparison that always evaluates to true or always to false.
In statically-typed languages with fixed-width numeric types, primitive numeric types have value ranges defined by the language specification:
When you compare a variable of one of these types against a constant that is outside its range, the type system guarantees the result before the
program even runs. For example, an 8-bit signed integer variable can never be greater than 127, so a comparison checking if it exceeds 200 will always
be false.
These comparisons indicate one of several problems:
false) or always executes (if always
true)Such comparisons make the code confusing and harder to maintain. They may also hide genuine bugs where the developer’s intent does not match the actual behavior.
In Java, these types are named: byte (8-bit signed), short (16-bit signed), char (16-bit unsigned),
int (32-bit signed), and long (64-bit signed). Equality tests on float and double variables are
covered by rule {rule:java:S1244} instead.
The constant does not have to be an integer: a floating-point constant compared against an integral variable is decided the same way, so l
> 1e30 is always false for a long variable.
Impossible comparisons create several problems:
false, the code inside the conditional block will never execute.
When always true, the else branch becomes unreachable.Ensure the constant is within the variable’s value range. If the constant is intentional, declare the variable as a wider type. For
long, there is no wider integral type, so the fix is to correct the constant or reconsider the logic.
This rule applies to primitive types only. Comparisons on boxed types such as Byte or Long are not reported.
byte b = 0;
if (b > 200) { // Noncompliant
// This code never executes
doSomething();
}
int b = getUserInput();
if (b > 200) {
// With an int, b can actually exceed 200
doSomething();
}