Java Reference
In-Depth Information
If the value of the divisor for an integer remainder operator is 0 , then an ArithmeticException
is thrown.
Example 15.17.3-1. Integer Remainder Operator
Click here to view code image
class Test1 {
public static void main(String[] args) {
int a = 5%3; // 2
int b = 5/3; // 1
System.out.println("5%3 produces " + a +
" (note that 5/3 produces " + b + ")");
int c = 5%(-3); // 2
int d = 5/(-3); // -1
System.out.println("5%(-3) produces " + c +
" (note that 5/(-3) produces " + d + ")");
int e = (-5)%3; // -2
int f = (-5)/3; // -1
System.out.println("(-5)%3 produces " + e +
" (note that (-5)/3 produces " + f + ")");
int g = (-5)%(-3); // -2
int h = (-5)/(-3); // 1
System.out.println("(-5)%(-3) produces " + g +
" (note that (-5)/(-3) produces " + h + ")");
}
}
This program produces the output:
Click here to view code image
5%3 produces 2 (note that 5/3 produces 1)
5%(-3) produces 2 (note that 5/(-3) produces -1)
(-5)%3 produces -2 (note that (-5)/3 produces -1)
(-5)%(-3) produces -2 (note that (-5)/(-3) produces 1)
The result of a floating-point remainder operation as computed by the % operator is not
the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754
remainder operation computes the remainder from a rounding division, not a truncating di-
vision, and so its behavior is not analogous to that of the usual integer remainder operator.
Instead, the Java programming language defines % on floating-point operations to behave
in a manner analogous to that of the integer remainder operator; this may be compared with
the C library function fmod . The IEEE 754 remainder operation may be computed by the
library routine Math.IEEEremainder .
Search WWH ::




Custom Search