This rule raises an issue when an integer calculation always overflows or uses an overflow-prone midpoint formula.

Why is this an issue?

Java does not report integer overflow. When an int or long calculation exceeds the range of its result type, the value silently wraps around.

The wrapped value can produce an incorrect index, size, limit, midpoint, or security-relevant result.

Widening the destination type does not protect a calculation performed with narrower operands. At least one operand must be widened before the operation. When overflow must be rejected, use an exact arithmetic method such as Math.addExact.

For ordered non-negative bounds, calculate a midpoint by subtracting the lower bound before adding it back.

Code examples

Noncompliant code example

int total = Integer.MAX_VALUE + 1; // Noncompliant

Compliant solution

long total = (long) Integer.MAX_VALUE + 1;

Noncompliant code example

int delta = Integer.MIN_VALUE - 1; // Noncompliant

Compliant solution

long delta = (long) Integer.MIN_VALUE - 1;

Noncompliant code example

int size = 1_000_000 * 10_000; // Noncompliant

Compliant solution

long size = 1_000_000L * 10_000;

Noncompliant code example

final int value = Integer.MIN_VALUE;
int opposite = -value; // Noncompliant

Compliant solution

final int value = Integer.MIN_VALUE;
long opposite = -(long) value;

Noncompliant code example

int midpoint = (low + high) / 2; // Noncompliant

Compliant solution

int midpoint = low + (high - low) / 2;

Noncompliant code example

final int increment = 1;
int next = Integer.MAX_VALUE + increment; // Noncompliant

Compliant solution

final int increment = 1;
int next = Math.addExact(Integer.MAX_VALUE, increment);

Resources

Documentation

Related rules