In this post, we will see about modulo or modulus operator in java.
Table of Contents
Modulo operator(%
) is used to find the remainder
when one integer is divided by another integer.
Modulo operator Syntax
1 2 3 |
int remainder = int % int; |
We can’t use modulo with any other data type other than int. If we use it with other data types, it will give compilation error.
For example:
1 2 3 4 5 6 7 |
// compiles successfully int rem = 10%3; // won't compile int rem = 10%3.0; |
Let’s see a simple example of modulo operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class ModuloOperatorMain { public static void main(String[] args) { int a= 15; int b = 4; int rem = a%b; System.out.println("15%4 = "+rem); } } |
Output:
When we divide 15 with 4, remainder is 3.
Modulo operator usages
Even odd program
Modulo operator is used to check if number is even or odd.
If number%2
is 0, then number is even
else odd
.
Let’s see program with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class ModuloOperatorMain { public static void main(String[] args) { int num =23; if(num%2 ==0) { System.out.println("Number is even"); } else { System.out.println("Number is odd"); } } } |
When you run above program, you will get below output:
Prime number program
Modulo operator is used to check if number is divisible by another number or not in prime number program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; public class ModuloOperatorMain { public static void main(String[] args) { System.out.println("is 91 Prime: "+isPrime(91)); System.out.println("is 43 Prime: "+isPrime(43)); System.out.println("is 61 Prime: "+isPrime(61)); } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } } |
Output:
is 43 Prime: true
is 61 Prime: true
I have highlighted the line where we are using modolu operator to check if number is divisible by another number.
Modulo operator behaviour with negative integer
When we use modulo operator with negative integer, it takes sign from dividend.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class ModuloOperatorMain { public static void main(String[] args) { System.out.println("-15%4 ="+(-15%4)); System.out.println("15%-4 ="+(15%-4)); } } |
Output:
15%-4 =3
As you can clearly see, remainder got sign from dividend.
That’s all about Modulo operator in java.