The Java Language Specification (JLS), §15.17.3, "Remainder Operator %" [JLS 2013], states,

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor.

The result of the remainder operator has the same sign as the dividend (the first operand in the expression):

5 % 3 produces 2
5 % (-3) produces 2
(-5) % 3 produces -2
(-5) % (-3) produces -2

As a result, code that depends on the remainder operation to always return a positive result is erroneous.

Noncompliant Code Example

This noncompliant code example uses the integer hashKey as an index into the hash array. 

private int SIZE = 16;	
public int[] hash = new int[SIZE];
	
public int lookup(int hashKey) {
  return hash[hashKey % SIZE];
}

A negative hash key produces a negative result from the remainder operator, causing the lookup() method to throw java.lang.ArrayIndexOutOfBoundsException.

Compliant Solution

This compliant solution calls the imod() method, which always returns a positive remainder:

// Method imod() gives nonnegative result
private int SIZE = 16;
public int[] hash = new int[SIZE];

private int imod(int i, int j) {
  int temp = i % j;
  return (temp < 0) ? -temp : temp; 
  // Unary minus will succeed without overflow  
  // because temp cannot be Integer.MIN_VALUE
}
	
public int lookup(int hashKey) {
  return hash[imod(hashKey, SIZE)];
}

Applicability

Incorrectly assuming a positive remainder from a remainder operation can result in erroneous code.

Automated Detection

ToolVersionCheckerDescription
SonarQubeS2197 

 

Bibliography

[JLS 2013]

§15.17.3, "Remainder Operator %"