In programs we often use the modulo division operator to compute remainders. A "%" performs modulo division. It returns the part left over when the numbers are divided.
In loops, modulo can alternate behavior—we can do something only when an index is evenly divisible by a number. In hash codes, we can convert a number to fit in a range.
Here we see the results of modulo division. It returns the remainder of a division—so 90 goes into 100 once, leaving 10 (the remainder).
public class Program { public static void main(String[] args) { int result = 1000 % 90; // Remainder is 10. System.out.println(result); result = 100 % 90; // Remainder is also 10. System.out.println(result); result = 81 % 80; // Remainder is 1. System.out.println(result); result = 1 % 1; // Remainder is 0. System.out.println(result); } }10 10 1 0
This program loops through the values 0 through 9. It sees if each number is divisible by 4, 3 and 2. It creates a String
for each number that indicates divisibility.
public class Program { public static void main(String[] args) { for (int i = 0; i < 10; i++) { String line = Integer.toString(i) + ":"; // ... See if number is divisible evenly by 4, 3 and 2. if (i % 4 == 0) { line += " %4"; } if (i % 3 == 0) { line += " %3"; } if (i % 2 == 0) { line += " %2"; } System.out.println(line); } } }0: %4 %3 %2 1: 2: %2 3: %3 4: %4 %2 5: 6: %3 %2 7: 8: %4 %2 9: %3
Some numbers like 2 or 4 are even. Others like 1 or 3 are odd. This is a number's parity. We use modulo to determine if a number is even or odd.
public class Program { public static boolean isEven(int value) { return (value % 2) == 0; } public static boolean isOdd(int value) { // ... Odd numbers can return either -1 or 1. return (value % 2) != 0; } public static void main(String[] args) { // Check parity of numbers. for (int i = -5; i <= 5; i++) { System.out.println(Integer.toString(i) + ": " + isEven(i) + ", " + isOdd(i)); } } }-5: false, true -4: true, false -3: false, true -2: true, false -1: false, true 0: true, false 1: false, true 2: true, false 3: false, true 4: true, false 5: false, true
Sometimes we want to compute custom hash codes for a String
or other value. Modulo helps here. We can perform and computation and then use modulo to "limit" the number.
String
based on its characters and length. Then we ensure the value will not exceed 100 with a modulo.public class Program { public static void main(String[] args) { String key = "carrot"; int size = 100; // This integer will never exceed 99. // ... So we can use "hash" to assign into a 100-element array. int hash = ((key.charAt(0) * 89) + key.length()) % size; System.out.println(hash); } }17
Math.floorMod
Some Math methods compute a modulo division and combine this with another operation like floor. Please review the Math.floorMod
method.
Modulo is an essential operation in computer languages. It is helpful for hashing and controlling loop behavior. It is a lower-level operation, but still used widely in programs.