C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Often modulo returns 0—this means no remainder is left. We commonly test modulo divisions against zero.
Java program that uses modulo operator
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);
}
}
Output
10
10
1
0
Tip: We can use a similar approach to determine if a number is odd or even—please see the next examples.
Java program that checks for evenly divisible numbers
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);
}
}
}
Output
0: %4 %3 %2
1:
2: %2
3: %3
4: %4 %2
5:
6: %3 %2
7:
8: %4 %2
9: %3
Warning: We cannot check for odd numbers by looking for a remainder of 1. This fails for negative numbers—we instead test against zero.
Java program that checks for even, odd numbers
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));
}
}
}
Output
-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
And: By applying a modulo division, we can ensure the resulting value can be used to index an array.
Here: We compute a hash code for a String based on its characters and length. Then we ensure the value will not exceed 100 with a modulo.
Array: We can then use the hash value to load from, or assign into, an array. This can optimize programs.
Java program that uses modulo, computes hash
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);
}
}
Output
17