Java Modulo Operator - Modulus Operator in Java With Examples

Java Modulo operator or modulus operator is used to getting the remainder when we divide an integer with another integer.


Java Modulo Operator Syntax

The % character is the modulus operator in Java. Its syntax is:

The modulus operator always returns an integer. If we try to use the modulo operator with any other type of variable, we will get a compilation error.


Modulus Operator Example

Let’s look at a simple example of using the modulus operator to find the remainder when two integers are divided.


Using Modulus Operator to check if an integer is even or odd

One of the simple use cases of the modulus operator is to test if an integer is odd or even.

Output:

Here are the utility methods to check if the integer is even or odd.


Using Modulus Operator to check if an integer is divided by another integer

We can use the modulo operator to check if an integer is divided by another integer or not.

Output:

Here is the implementation of a utility method to check if an integer is divided by another integer or not.


Modulus Operator with negative integers

When modulus operator is used with negative integers, the output retains the sign of the dividend.

By admin

Leave a Reply