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.

Why is this an issue?

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:

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.

What is the potential impact?

Impossible comparisons create several problems:

How to fix it

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.

Exceptions

This rule applies to primitive types only. Comparisons on boxed types such as Byte or Long are not reported.

Code examples

Noncompliant code example

byte b = 0;
if (b > 200) { // Noncompliant
    // This code never executes
    doSomething();
}

Compliant solution

int b = getUserInput();
if (b > 200) {
    // With an int, b can actually exceed 200
    doSomething();
}

Resources

Documentation

Related rules