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:

Spring Webflux with Kotlin
ExecutorService – Waiting for Threads to Finish
Java – Get Random Item/Element From a List
The Basics of Java Security
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Lớp Arrarys trong Java (Arrays Utility Class)
Guide to the Java Queue Interface
Java Byte Array to InputStream
How to Store Duplicate Keys in a Map in Java?
Hướng dẫn Java Design Pattern – Abstract Factory
Java Program to Implement Hash Tables with Double Hashing
Java Program to Implement Ternary Search Tree
String Operations with Java Streams
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Using JWT with Spring Security OAuth (legacy stack)
Functional Interface trong Java 8
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Convert XML to JSON Using Jackson
Java Program to implement Associate Array
An Intro to Spring Cloud Vault
Working with Tree Model Nodes in Jackson
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Implement WeakHashMap API
Java Program to Perform Quick Sort on Large Number of Elements
Redirect to Different Pages after Login with Spring Security
Java Program to find the maximum subarray sum O(n^2) time(naive method)
Java Program to Implement LinkedHashSet API
Spring Boot - OAuth2 with JWT
Spring Boot - Cloud Configuration Client
Hướng dẫn Java Design Pattern – Visitor