Java Reference
In-Depth Information
Remainder versus modulo.
In math, the value
x
mod
y
, or
x
modulo
y
, is the non-negative
remainder
r
that arises from dividing
x
by
y
. The value
x
mod
y
satisfies:
x = y*q+r
and
0≤r<y
(for some
quotient
q
, which is unique)
For
x≥0
,
x%y
and
x
mod
y
are the same. Consequently, many people call
%
the
mod operato
r. But
%
and
mod
differ when
x
is negative. For example:
-7
mod
5=3
, but
-7%5=-2
For
x<0
,
%
and
mod
are related by the formula:
x
mod
y = x%y+y
•
E1 + E2
is conventional
addition
, e.g.
4+10
evaluates to
14
.
•
E1 - E2
is conventional
subtraction
, e.g.
4-10
evaluates to
-6
.
•
E1 * E2
is conventional
multiplication
, e.g.
4*10
evaluates to
40
.
•
E1
/
E2 is
un
conventional
division
. To compute its value, compute con-
ventional division and throw away the fractional part of the result to yield
an integer. For example,
10 / 2
evaluates to
5
10 / (-2)
evaluates to
-5
13 / 3
evaluates to
4
(i.e. the integer part of
4.333...
)
14 / 3
evaluates to
4
(i.e. the integer part of
4.666...
)
13 / (-3)
evaluates to
-4
(that is, the integer part of
-4.333...
)
14 / (-3)
evaluates to
-4
(that is, the integer part of
-4.666...
)
Note that for E1 < 0 , E1 / E2 =
-
(E1
/
E2).
•
E1 % E2
is the remainder operation. For
E1
≥
0
and
E2 > 0
,
E1 % E2
is the
remainder when
E1
is (conventionally) divided by
E2
. For example,
6%3
evaluates to
0
7%3
evaluates to
1
8%3
evaluates to
2
For
E1
≥
0
and
E2 < 0
,
E1 % E2 = E1 % -E2
.
For
E1 < 0
,
-E1 % E2 = -(E1 % E2)
.
It is an error if
E2 = 0
(an
ArithmeticException
occurs).
Watch out for = versus ==.
A worldwide mathematical convention is that = denotes equality:
b
=c
evaluates to
true
or
false
depending on whether
b
and
c
have the same
value or not. Java, following C and C++, has gone against this mathematical
convention, using
==
for equality and
=
for the assignment statement. This one
affront to convention has caused more misunderstanding, confusion, and eco-
nomic loss than any other notational choice.
Search WWH ::
Custom Search