Java Reference
In-Depth Information
9.1.1. Integer Arithmetic
Integer arithmetic is modular two's-complement arithmeticthat is, if a
value exceeds the range of its type (
int
or
long
), it is reduced modulo
the range. So integer arithmetic never overflows or underflows but only
wraps.
Integer division truncates toward zero (
7/2
is
3
, and
-7/2
is
-3
). For in-
teger types, division and remainder obey the rule
(x/y)*y + x%y == x
So
7%2
is 1, and
-7%2
is 1. Dividing by zero or remainder by zero is invalid
for integer arithmetic and throws
ArithmeticException
.
Character arithmetic is integer arithmetic after the
char
is implicitly con-
9.1.2. Floating-Point Arithmetic
Floating-point arithmetic can overflow to infinity (become too large for
a
double
or
float
) or underflow (become too small for a
double
or
float
).
Underflow results in a loss of precision, possibly enough to yield a zero
infinity, is a NaN valuefor "Not-a-Number."
[1]
Detecting non-zero underflows is a non-trivial task that is beyond the scope of this topic.
Arithmetic with finite operands performs as expected, within the limits of
precision of
double
or
float
. Signs of floating-point arithmetic results are
also as expected. Multiplying two numbers having the same sign results
in a positive value; multiplying two numbers having opposite signs res-
ults in a negative value.