Java also supports a fifth arithmetic operator,
%
, called the
remainder operator. Like the other four basic arithmetic operators it takes two operands. Mathematically it returns the remainder after dividing the first number by the second, using truncating division. For instance,
5 % 2
evaluates to 1 since 2 goes into 5 two times with a remainder of 1.
While you may not have heard of remainder as an operator, think back to elementary school math when you first learned long division, before you learned about decimals. You probably learned how to give the answer to a long division that didnβt divide evenly in terms of the number of even divisions and the remainder. The remainder is what is returned by the
%
operator. In the figures below, the remainders are the same values that would be returned by
2 % 3
and
5 % 2
.
Sometimes peopleβincluding Professor Lewis in the next videoβwill call
%
the
modulo, or
mod, operator. That is not actually correct though the difference between remainder and modulo only matters when the signs of the operands differ. (The difference has to do with what kind of division is done before finding the remainder; the remainder operator is based on truncating integer division where the quotient is truncated toward zero while modulo is based on
Euclidean division which truncates toward negative infinity.) With operands of the same sign, remainder and modulo give the same results. Java does have a method
Math.floorMod
in the
Math
class if you need to use modulo instead of remainder, but
%
is all you need in the AP exam and it will only be used with positive operands.
Note 2.3.2.
Remember that the value of
x % y
when
x
is smaller than
y
is always
x
. Since
y
canβt go into
x
at all (goes in 0 times), the result is just
x
. So
2 % 3
is
2
since
2 < 3
.