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:

Map to String Conversion in Java
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Compact Strings in Java 9
Java Program to Implement Gaussian Elimination Algorithm
Guide to Spring 5 WebFlux
Java Program to Implement Jarvis Algorithm
Java Program to Implement JobStateReasons API
Guide to Mustache with Spring Boot
Java Program to Find Transpose of a Graph Matrix
Returning Custom Status Codes from Spring Controllers
Spring REST API + OAuth2 + Angular
Working with Tree Model Nodes in Jackson
Instance Profile Credentials using Spring Cloud
Java Program to Implement Segment Tree
Java Program to Implement Heap Sort Using Library Functions
ExecutorService – Waiting for Threads to Finish
SOAP Web service: Authentication trong JAX-WS
Java Program to Implement EnumMap API
Java Program to Implement Network Flow Problem
Java Program to Implement Park-Miller Random Number Generation Algorithm
Guide to Character Encoding
Introduction to Apache Commons Text
Spring MVC + Thymeleaf 3.0: New Features
A Guide to Apache Commons Collections CollectionUtils
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Java Program to find the number of occurrences of a given number using Binary Search approach
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Merging Two Maps with Java 8
Java Program to Check if a Matrix is Invertible
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
LinkedList trong java