The Modulo Operator in Java

1. Overview

In this short tutorial, we’re going to show what the modulo operator is, and how we can use it with Java for some common use cases.

2. The Modulo Operator

Let’s start 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) – in this case, 3.

Due to 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’re trying to use zero as the right side operand:

@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException() {
    double result = 1 / 0;
}

@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException() {
    double result = 1 % 0;
}

3. Common Use Cases

The most common use case for the modulo operator is to find out if a given number is odd or even.

If the outcome of the modulo operation between any number and two is equal to one, it’s an odd number:

@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1() {
    assertThat(3 % 2).isEqualTo(1);
}

On the other hand, if the result is zero (i.e. there is no remainder), it’s an even number:

@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0() {
    assertThat(4 % 2).isEqualTo(0);
}

Another good use of the modulo operation is to keep track of the index of the next free spot in a circular array.

In a simple implementation of a circular queue for int values, the elements are kept in a fixed-size array.

Any time we want to push an element to our circular queue, we just compute the next free position by computing the modulo of the number of items we have already inserted plus 1 and the queue capacity:

@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds() {
    int QUEUE_CAPACITY= 10;
    int[] circularQueue = new int[QUEUE_CAPACITY];
    int itemsInserted = 0;
    for (int value = 0; value < 1000; value++) {
        int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
        circularQueue[writeIndex] = value;
    }
}

Using the modulo operator we prevent writeIndex to fall out of the boundaries of the array, therefore, we’ll never get an ArrayIndexOutOfBoundsException.

However, once we insert more than QUEUE_CAPACITY items, the next item will overwrite the first.

4. Conclusion

The modulo operator is used to compute the remainder of an integer division that otherwise lost.

It’s useful to do simple things like figuring out if a given number is even or odd, as well as more complex tasks like tracking the next writing position in a circular array.

The example code is available in the GitHub repository.

Related posts:

Java Program to Check whether Graph is Biconnected
Inheritance and Composition (Is-a vs Has-a relationship) in Java
New Features in Java 10
Custom Error Pages with Spring MVC
Java Program to Implement AttributeList API
Java Program to Implement Insertion Sort
Tránh lỗi NullPointerException trong Java như thế nào?
OAuth 2.0 Resource Server With Spring Security 5
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Jackson – Marshall String to JsonNode
Guide to Spring @Autowired
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Command-Line Arguments in Java
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Giới thiệu Google Guice – Dependency injection (DI) framework
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Introduction to Spring Cloud OpenFeign
Transactions with Spring and JPA
Model, ModelMap, and ModelAndView in Spring MVC
Java Program to Implement Sorted Vector
Changing Annotation Parameters At Runtime
Serverless Functions with Spring Cloud Function
Concatenating Strings In Java
Java Program to Implement Rolling Hash
Java Program to Implement Depth-limited Search
Java Program to Compute Cross Product of Two Vectors
Java Program to Find Nearest Neighbor for Dynamic Data Set
How to use the Spring FactoryBean?
Copy a List to Another List in Java