Modulo operator in java

In this post, we will see about modulo or modulus operator in java.

Modulo operator(%) is used to find the remainder when one integer is divided by another integer.

Modulo operator Syntax

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:

Let’s see a simple example of modulo operator.

Output:

15%4 = 3

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:

When you run above program, you will get below output:

Number is odd

Prime number program

Modulo operator is used to check if number is divisible by another number or not in prime number program.

Output:

is 91 Prime: false
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.

Output:

-15%4 =-3
15%-4 =3

As you can clearly see, remainder got sign from dividend.

That’s all about Modulo operator in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *