Java Reference
In-Depth Information
The remainder operator
Oneoftheoperatorsin Table7-1 requiresadditionalcomment.The%opera-
torgivestheremainderofadivision.The%symbolisalsocalledthe modu-
lus operator . Its action is limited to integer operands. The following code
fragment shows its use:
int val1 = 14;
int result = val1 % 3;
In this case, the value of the variable result is 2 since this is the remain-
der of dividing 14 by 3.
Programmers note:
Weprefertocallthe%symboltheremainderoperatorsincetheword
“modulus” is sometimes used in mathematics for the absolute value.
Inthissensethemathematicalexpression|-4|issaidtobethemodu-
lus of -4, which is 4.
Theremainderofadivisionfindsmanyusesinmathematicsandinpro-
gramming. Operations based on the remainder are sometimes called
“clock arithmetic.”Thisisdueto thefact that theconventionalclock face
is divided into 12 hours which repeat in cycles. We can say that the
modulo of a clock is 12. The hour-of-day from the present time, after any
number of hours, can be easily calculated by the remainder of dividing
the number of hours by 12 and adding this value to the present time.
Suppose it is 4 o'clock and you want to calculate the hour-of-day after
27 hours have elapsed. The remainder of 27/12 is 3. The hour-of-day is
then4+3,which is 7 o'clock. In Java you can obtain the remainder with a
single operator. The following code fragment shows the calculations in
this example:
int thisHour = 4;
int hoursPassed = 27;
int hourOfDay = thisHour + (hoursPassed % 12);
Note that the expression
hoursPassed % 12
givestheremainderof27/12,whichisthenaddedtothecurrenthourtoob-
tain the new hour-of-day.
Search WWH ::




Custom Search