Member-only story
Modulo Operator in Java
1. Overview
In this tutorial we will learn about modulo operator, how can we use it in Java common use cases.
2. The Modulo Operator
Let’s begin with the shortcomings of simple division in Java.
If the operands on both sides of the division operator have type int, the result of the operation is another int:
@Test
public void whenIntegerDivision_thenLosesRemainder() {
assertThat(11 / 4).isEqualTo(2);
}The same division gives us a different result when at least one of the operands has type float or double:
@Test
public void whenDoubleDivision_thenKeepsRemainder() {
assertThat(11 / 4.0).isEqualTo(2.75);
}We can observe that we lose the remainder of a division operation when dividing integers.
The modulo operator gives us exactly this remainder:
@Test
public void whenModulo_thenReturnsRemainder() {
assertThat(11 % 4).isEqualTo(3);
}The remainder is what remains after dividing 11 (the dividend) by 4 (the divisor), which in this case is 3.
For the same reason a division by zero isn’t possible, it’s not possible to use the modulo operator when the right-side argument is zero.
Both the division and the modulo operation throw an ArithmeticException when we try to use zero as the right side operand:








