EN
Modulo in java - syntax, how to use it with examples
12 points
Modulo operator in java:
xxxxxxxxxx
1
%
Examples:
A lof of examples with println of each operation,
it will explain all doubts how it works.
xxxxxxxxxx
1
System.out.println(0 % 3); // 0
2
System.out.println(1 % 3); // 1
3
System.out.println(2 % 3); // 2
4
System.out.println(3 % 3); // 0
5
System.out.println(4 % 3); // 1
6
System.out.println(5 % 3); // 2
7
System.out.println(6 % 3); // 0
8
System.out.println(7 % 3); // 1
9
System.out.println(8 % 3); // 2
10
System.out.println(9 % 3); // 0
modulo with negative numbers
xxxxxxxxxx
1
System.out.println(-4 % 3); // -1
2
System.out.println(-3 % 3); // 0
3
System.out.println(-2 % 3); // -2
4
System.out.println(-1 % 3); // -1
compare - division vs modulo
xxxxxxxxxx
1
// DIVISION:
2
System.out.println(19 / 20); // 0
3
System.out.println(20 / 20); // 1
4
System.out.println(21 / 20); // 1
5
System.out.println(40 / 20); // 2
6
System.out.println(41 / 20); // 2
7
8
// MODULO:
9
System.out.println(19 % 20); // 19
10
System.out.println(20 % 20); // 0
11
System.out.println(21 % 20); // 1
12
System.out.println(40 % 20); // 0
13
System.out.println(41 % 20); // 1
Check if number is even
xxxxxxxxxx
1
int num = 2;
2
if ((num % 2) == 0) {
3
System.out.println("even number"); // even number
4
}
Check if number is odd
xxxxxxxxxx
1
int num = 1;
2
if ((num % 1) == 0) {
3
System.out.println("odd number"); // odd number
4
}
- In mathematics - https://en.wikipedia.org/wiki/Modular_arithmetic
- In computing - https://en.wikipedia.org/wiki/Modulo_operation
- Even and Odd numbers - https://en.wikipedia.org/wiki/Parity_(mathematics)