Java Modulus / Modulo operator – Examples and Uses

The Java modulus ‘%’ operator is one of numerous operators built into the Java programming language. The operator is used to calculate the remainder of the division between two numbers. First, let us discuss how the operator works.

 

How to use the ‘%’ operator:

 

The ‘%’ operator requires two operands. The first is the number on which the operator will be applied upon and the second is the divisor. The result should be the remainder that would remain if we had divided the first number by the divisor. An example usage of the operator in Java can be as follows:

 

 

In this case the result will be 5.

 

 

 

Another way to describe the modulus operation is that it finds out the first remaining number which is smaller than the divisor, if we repeatedly subtracted the divisor from the numerator. 

 

For example:

 

 

Uses of the modulo operator:

 

The ‘%’ operator can be used in many situations within a Java program. Let us check some use cases:

 

1 – Checking if a number is even or odd:

 

 

2 – Checking for even distribution:

 

In some situations, it is important to insure equality. For example, if a specific number of items can be evenly distributed on different channels/nodes/entities. In this case, the condition can be calculated with the modulus operator:

 

 

 

3 – Converting seconds to hours, minutes and seconds:

 

In this example, we take an input of the total amount of seconds and we calculate the number of hours, remaining minutes and seconds.

 

 

The output of the program above would be:

 

 

Other uses:

 

The operator can be used in many other situations. For example, to find out if a number is a prime number, or in an accounting application that is used to calculate money installments and remaining amounts.