Modulo Operator in Java

JavaJavaBeginner
Practice Now

Introduction

The Modulo operator is a mathematical operator that is used to find the remainder of the division of two numbers. This operator is represented by the symbol %. In Java, the modulo operator returns the remainder of dividing the first number by the second number. This Lab will guide you through some of the use cases of this operator.

Modulo Operator Example

In this step, we will see the basic syntax of the modulo operator and how it can be used on integer and floating-point variables. We will also see how it handles negative numbers.

  1. Create a new file named ModuloOperatorDemo.java using the touch command.
  2. Open the file in a text editor such as nano.
  3. Add the following code to the file:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        System.out.println("10 % 3 = " + 10 % 3);
        System.out.println("3 % 10 = " + 3 % 10);
        System.out.println("10.0 % 3.0 = " + 10.0 % 3.0);
        System.out.println("10.0 % 3 = " + 10.0 % 3);
        System.out.println("-10 % 3 = " + -10 % 3);
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
10 % 3 = 1
3 % 10 = 3
10.0 % 3.0 = 1.0
10.0 % 3 = 1.0
-10 % 3 = -1

Need for Modulo Operator

In this step, we will discuss why the modulo operator is needed when using the division operator.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        int dividend = 10;
        int divisor = 3;
        int remainder = dividend - (divisor * (dividend/divisor));
        System.out.print("The remainder is: " + remainder);
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
The remainder is: 1

When Dividend or Divisor is not an Integer

In this step, we will see how the modulo operator can handle decimal numbers.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        double dividend = 10;
        int divisor = 3;
        double remainder = dividend - (divisor * (dividend/divisor));
        System.out.print("The remainder is: " + remainder);
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
The remainder is: 0.0
  1. Modify the code in the file as follows:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        double dividend = 10;
        int divisor = 3;
        double remainder = dividend % divisor;
        System.out.print("The remainder is: " + remainder);
    }
}
  1. Save the file and exit the text editor.
  2. Recompile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should now output the following:
The remainder is: 1.0

ArithmeticException by Modulo Operator

In this step, we will see how the modulo operator throws an exception if the divisor is zero.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        System.out.print("The remainder is: " + 10 % 0);
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should throw an ArithmeticException as follows:
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ModuloOperatorDemo.main(ModuloOperatorDemo.java:3)

Find Even Numbers

In this step, we will see how the modulo operator can be used to check whether a number is even or odd.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        int[] arr = {7, 5, 2, 4, 6, 19, 18, 25, 22};
        for(int i=0; i<arr.length; i++)
        {
            int num = arr[i];
            if((num % 2) == 0)
                System.out.println(num + " is even.");
            else
                System.out.println(num + " is NOT even.");
        }
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
7 is NOT even.
5 is NOT even.
2 is even.
4 is even.
6 is even.
19 is NOT even.
18 is even.
25 is NOT even.
22 is even.

Convert Seconds to Minutes and Seconds

In this step, we will see how the modulo operator can be used to convert seconds into minutes and seconds.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        int seconds = 401;
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        System.out.print(seconds + " seconds is equal to " + minutes +" minutes " + remainingSeconds + " seconds");
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
401 seconds is equal to 6 minutes 41 seconds

Fetching individual digits of an integer

In this step, we will see how the modulo operator can be used to extract individual digits from a number.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        int num = 7912064;
        while(num > 0)
        {
            int lastDigit = num % 10;
            num = num / 10;
            System.out.print(lastDigit + " ");
        }
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
4 6 0 2 1 9 7

Repeat something every nth time

In this step, we will see how the modulo operator can be used to repeat an action every nth time.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        for(int i = 1; i <= 30; i++)
        {
            if(i % 5 == 0)
                System.out.println("Do Something");
        }
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
Do Something
Do Something
Do Something
Do Something
Do Something
Do Something

Restrict a Number to a certain range

In this step, we will see how the modulo operator can be used to limit a number to a certain range.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        String[] dayNames = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        int dayOfTheMonth1 = 21;
        String dayName1 = dayNames[(dayOfTheMonth1 - 1) % 7];
        int dayOfTheMonth2 = 12;
        String dayName2 = dayNames[(dayOfTheMonth2 - 1) % 7];

        System.out.println(dayOfTheMonth1 + " occurs on " + dayName1);
        System.out.println(dayOfTheMonth2 + " occurs on " + dayName2);
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
21 occurs on Sunday
12 occurs on Friday

Make a number completely divisible by another number

In this step, we will see how the modulo operator can be used to make a number completely divisible by another number.

  1. Open the ModuloOperatorDemo.java file in a text editor.
  2. Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
    public static void main(String[] args)
    {
        int X = 291;
        int Y = 17;

        int remainder = X % Y;
        X = X - remainder;
        System.out.println("The minimum number to subtract is: " + remainder);
        System.out.println("The number after subtraction is: " + X);
    }
}
  1. Save the file and exit the text editor.
  2. Compile the code using the command javac ModuloOperatorDemo.java.
  3. Run the code using the command java ModuloOperatorDemo.
  4. The code should output the following:
The minimum number to subtract is: 2
The number after subtraction is: 289

Summary

The modulo operator is a mathematical operator that is used to find the remainder of the division of two numbers. In this lab, we covered various use cases of the modulo operator such as checking whether a number is even, converting seconds to minutes and seconds, extracting individual digits, repeating an action every nth time, limiting a number to a certain range, and making a number completely divisible by another number. Keep in mind that when using the modulo operator, the divisor cannot be zero as it will throw an ArithmeticException.

Other Java Tutorials you may like