Java Reference
In-Depth Information
These two division operators should be familiar if you recall how long-division
calculations are performed:
31
34
1079
102
_____
59
34
___
25
Here, dividing 1079 by 34 yields 31 with a remainder of 25. Using arithmetic
operators, the problem would be described like this:
1079 / 34 evaluates to 31
1079 % 34 evaluates to 25
It takes a while to get used to integer division in Java. When you are using the
division operator ( / ), the key thing to keep in mind is that it truncates anything after
the decimal point. So, if you imagine computing an answer on a calculator, just think
of ignoring anything after the decimal point:
19/5 is 3.8 on a calculator, so 19/5 evaluates to 3
207/10 is 20.7 on a calculator, so 207/10 evaluates to 20
3/8 is 0.375 on a calculator, so 3/8 evaluates to 0
The remainder operator ( % ) is usually referred to as the “mod operator,” or simply
“mod.” The mod operator lets you know how much was left unaccounted for by the
truncating division operator. For example, given the previous examples, you'd com-
pute the mod results as shown in Table 2.3.
In each case, you figure out how much of the number is accounted for by the trun-
cating division operator. The mod operator gives you any excess (the remainder).
When you put this into a formula, you can think of the mod operator as behaving as
follows:
x % y = x (x / y) * y
Table 2.3
Examples of Mod Operator
What does division
How much
Mod problem
First divide
account for?
is left over?
Answer
19/5 is 3
3 * 5 is 15
19
15 is 4
19 % 5
4
207/10 is 20
20 * 10 is 200
207
200 is 7
207 % 10
7
3/8 is 0
0 * 8 is 0
3
0is3
3 % 8
3
 
 
Search WWH ::




Custom Search