11.8: Modulus Operator
- Page ID
- 17726
Let’s take the example one step further: suppose you have a measurement in inches and you want to convert to feet and inches. The goal is divide by 12 (the number of inches in a foot) and keep the remainder.
We have already seen the division operator (/
), which computes the quotient of two numbers. If the numbers are integers, it performs integer division. Java also provides the modulus operator (\%
), which divides two numbers and computes the remainder.
Using division and modulus, we can convert to feet and inches like this:
quotient = 76 / 12; // division remainder = 76 % 12; // modulus
The first line yields 6. The second line, which is pronounced “76 mod 12”, yields 4. So 76 inches is 6 feet, 4 inches.
The modulus operator looks like a percent sign, but you might find it helpful to think of it as a division sign (÷) rotated to the left.
The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x \% y
is zero, then x
is divisible by y
. You can use modulus to “extract” digits from a number: x \% 10
yields the rightmost digit of x
, and x \% 100
yields the last two digits. Also, many encryption algorithms use the modulus operator extensively.