The Modulo Operator In Java

The Modulo operator in Java is quite a useful mechanism. Java provides us with basic arithmetic operators for addition, subtraction, division, multiplication etc. We can easily divide two integers in Java.

1
2
final int result = 13 / 4;
System.out.println(result);

If we execute the above code we will get a result of 3. However, what happens if we need the remainder of this operation. Well, this is what we can use the modulo operator for.

In this short tutorial we will discuss the Modulo operator in Java, and some of its use cases.

Modulo Operator

The modulo operator has some useful use cases and at times it can be a handy programming tool.

The modulo operator is represented by the % symbol. It is a binary operator that takes two operands. Moreover, when it is applied it performs a division and returns the remainder.

1
2
3
4
5
@Test
public void modulo() {
    final int result = 13 % 4;
    assertEquals(1, result);
}

Note the result of applying the modulo operator returns the integer value 1. We could also obtain a decimal value by using a float or a double.

1
2
3
4
5
@Test
public void modulo_decimal() {
    final float result = 13 % 4;
    assertEquals(1.0, result, 0);
}

When we apply the modulo operator to floating point numbers it is important to be aware that there can be issues related to Floating Point Precision.

Moreover, just like you can’t divide by zero, the right hand operator of the modulo operator cannot be zero. If this is the case it will result in an ArithmeticException.

1
2
3
4
@Test(expected = ArithmeticException.class)
public void modulo_divideByZero() {
    final int result = 13 % 0;
}

Testing If A Number Is Even

We can test if a number is even using the Modulo operator. This is because any number divided by 2 has a remainder of 0.

1
2
3
4
5
6
7
8
9
@Test
public void isEven() {
    assertEquals(0, 4 % 2);
}

@Test
public void isOdd() {
    assertNotEquals(0, 5 % 2);
}

Perform An Action Every Nth Time

This can be a handy mechanism. For example, if we have a loop and we want to perform a task every nth time.

1
2
3
4
5
for (int i = 0; i < 100; i++) {
    if (i % 3 == 0) {
        //do something every three iterations
    }
}

Show Seconds As Units Of Time

We can also use the modulo operator to convert a number of seconds that have elapsed, into hours, minutes and seconds.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Test
public void secondsAsUnits() {
    final int elapsedSeconds = 643;
    final int hours = elapsedSeconds / 3600;
    final int minutes = (elapsedSeconds / 60) % 60;
    final int seconds = elapsedSeconds % 60;

    final String expected = "0:10:43";
    final String actual = hours + ":" + minutes + ":" + seconds;

    assertEquals(expected, actual);
}

Maintain A Bounded Index

The modulo operator can also be used, to maintain a bounded index. For example calculating the next index to write to in an array, without exceeding the arrays bounds.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Test
public void boundedIndex_contrivedAddition() {
    final int expectedSum = 15;
    int[] calculatorMemory = new int[]{0,0};
    int arrWriteIndex = 0;

    for(int index=0; index<5; index++) {
        arrWriteIndex = index % calculatorMemory.length;
        int arrReadIndex = Math.abs(arrWriteIndex -1);
        final int value = calculatorMemory[arrReadIndex] + (index + 1);
        calculatorMemory[arrWriteIndex] = value;
    }

    assertEquals(expectedSum,calculatorMemory[arrWriteIndex]);
}

In the above example we sum all the integers from 1 to 5. The modulo operator is used to keep the array index for the array calculatorMemory in bounds.

Conclusion

In this short tutorial we looked at the modulo operator in Java. We looked at how to use it and some of its common use cases.