Java Reference
In-Depth Information
moreover, the magnitude of the result is always less than the magnitude of the divi-
sor.
Theresultoftheremainderoperatorhasthesamesignasthedividend(thefirstoperand
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
Thisnoncompliantcodeexampleusestheinteger hashKey asanindexintothe hash array:
Click here to view code image
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 a java.lang.ArrayIndexOutOfBoundsException .
Compliant Solution
This compliant solution calls the imod() method which always returns a positive re-
mainder:
Click here to view code image
// 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;
Search WWH ::




Custom Search