Modulo is one of the most popularly used arithmetic operators that is used to find the remainder of two values. It is also referred to as the “remainder” or the “modulus” operator and is denoted by the “%” symbol in Java. The return type of the modulo operator depends on the input type of the given operands. For instance, if both operands are integers then the remainder will also be an integer, if one of them or both are double then the remainder will also be double.
Quick Outline
- What is a Modulo Operator and How Does it Work in Java?
- Division Vs Modulo: What’s the Difference?
- Possible Exceptions While Working With Modulo Operator
- Modulo Operator Alternatives
- Final Thoughts
What is a Modulo Operator and How Does it Work in Java?
The modulo operator performs division on the given values and retrieves the remainder as an output. In Java, it is denoted with a percent sign “%”, as demonstrated in the following syntax:
dividend % divisor;
Graphical Representation of Modulo Operator:
There are numerous use cases of the modulo operator. Some of them are discussed below along with practical examples:
Case 1: Use the Modulo Operator to Find the Remainder of Two Integers
Declare and initialize a couple of integer-type variables in the main() method:
int dividend = 73;
int divisor = 6;
Use the modulo operator “%” on the given values and store the result in a new variable named “modulo”:
int modulo = dividend%divisor;
Print the computed result on the console:
System.out.println(dividend + "%" + divisor + " is equal to: "+ modulo);
Complete Code & Output
Case 2: Use the Modulo Operator to Find the Remainder of Two Double Values
Declare and initialize two double-type variables: “dividend” and “divisor”:
double dividend = 73.52;
double divisor = 6.73;
Use the modulo operator “%” on the provided values, store the result in a new variable named “modulo”, and print it on the console:
double modulo = dividend%divisor;
System.out.println(dividend + "%" + divisor + " = "+ modulo);
Complete Code & Output
Case 3: Use Modulo Operator to Check If a Number is Divisible By 3
The following example takes a number from the user and checks if it is divisible by 3. For this, first, import the Scanner class:
import java.util.Scanner;
Create a Scanner object and use it with nextInt() to get an integer value from the user:
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please Enter a Number");
int input = scannerObj.nextInt();
Use the modulus operator to find the remainder of the user-entered number for 3:
int modulo = input%3;
Now use the if-else statement to check if the user-entered number is divisible by 3:
if (modulo == 0)
{
System.out.println("Input Number is Divisible by 3");
}
else
{
System.out.println("Input Number is Not Divisible by 3");
}
Complete Code & Output
Case 4: Use Modulo Operator To Check if User-entered Value is a Prime Number
The first two steps are the same as the previous example, i.e., import the Scanner class and take user input. After this, create an integer-type variable and assign it a value of 0:
int flag = 0;
Now use a for loop and iterate it up to “input / 2”. Within for loop use the if statement to check if the user-entered value is divisible by any number. If it is divisible by any number, then break the loop:
for (int i = 2; i <= input/2; i++)
{
if (input % i == 0)
{
flag++;
break;
}
}
A number (>1) that is divisible by “itself” and “1” is said to be a prime number. Specify this condition in the if-else statement to check if the given value is a “prime number”:
if (flag == 0 && input != 1)
{ System.out.println(input + " is a Prime number");
}
else
{
System.out.println(input + " is Not a Prime number");
}
Complete Code & Output:
Case 5: Use Modulo Operator To Find Total Occurrences of Even and Odd Numbers in an Array
First, create an array of different integers, and use the “length” property on it to find its size:
int[] input = {2, 1, 3, 5, 6, 98, 91, 121, 0, 3};
int arrSize = input.length;
Declare and Initialize a couple of integer-type variables with a value of 0:
int evenCount =0, oddCount = 0;
Use the for loop to iterate over the given array and find the number of even and odd numbers. Within the for loop, use an if-else statement with the modulo operator to find the even and odd numbers in the array:
for (int i=0; i< arrSize; i++)
{
if (input[i]%2 == 0)
evenCount++;
else
oddCount++; }
Finally, use the “System.out.println()” method to display the number of even and odd values:
System.out.println("Total Even Numbers in the Given Array: " + evenCount);
System.out.println("Total Odd Numbers in the Given Array: " + oddCount);
Complete Code & Output:
Case 6: Use Modulo Operator on a Circular Array
The most frequent use case of the modulo operator is in circular arrays. A circular array is an array whose elements are connected with each other circularly. It is such that the first element is connected to a second element, a second element is connected to a third element, and so on until the last element is connected to the first element.
For instance, declare and initialize a simple string-type array:
String [] circularArray = { "j", "a", "v", "a", "b", "e", "a", "t"};
Now, iterate over the array using a for loop to print its elements:
for (int i = 4; i <= 11; i++) {
System.out.println(circularArray[i]);
}
The loop starts its iteration from index 4 and is expected to go on till index 11:
The last index of the given array is “7”. Therefore, Java throws an “IndexOutofBounds” exception when we try to access an element at the index 8 or above. To fix this exception, use the modulo operator as follows:
circularArray[arrayIndex % arraySize];
Use the length property to find the size of the given array. Then iterate the loop until a specific number and within the loop’s body use the modulo operator with the array size to iterate over each element of the circular array:
int arraySize = circularArray.length;
for (int i = 4; i <= 11; i++) {
System.out.println(circularArray[i%arraySize]);
}
Complete Code & Output:
Case 7: Use Modulo Operator To Check Leap Year
Use the modulus operator to check if the user enters a leap year. For this, first, import the Scanner class, and take a “Year” from the user as input:
Scanner scannerObj = new Scanner(System.in);
System.out.println("Enter a Year");
int inputYear = scannerObj.nextInt();
Now use the modulo operator with the if-else statement to check if the user entered a leap year:
if ((inputYear % 4 == 0 && inputYear % 100 != 0) || inputYear % 400 == 0) {
System.out.println("It's a Leap year.");
}
else {
System.out.println("Not a leap year.");
}
If a year is fully divisible by “4”, then it is known as a leap year. However, a century year is said to be a leap year if it is divisible by 400.
Complete Code & Output:
Case 8: Use Modulo Operator To Create Cyclic Loops
To create a cyclic loop specify a number up to which you want to iterate a loop. After this, use the modulus operator with a divisor based on which you want to create a cycle:
for (int num = 0; num < 12; num++) {
int cycleVal = num % 4;
System.out.println(cycleVal);
}
Complete Code & Output:
Case 9: Use Modulo Operator To Convert Minutes to Hours
First, use the Scanner class to take minutes to be converted from the user:
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please Enter Total Minutes");
int inputMinutes = scannerObj.nextInt();
Use the division operator to calculate the total hours and the modulo operator to find the remaining minutes:
int hours = minutes / 60;
int remainingMinutes = minutes % 60;
System.out.print(minutes + " minutes = "
+ hours + " hours "
+ remainingminutes + " minutes");
Complete Code & Output:
Case 10: Use Modulo Operator on Negative Values
The modulo operator retrieves the output according to the sign associated with the dividend. For demonstration, first, use the Modulo operator with the negative dividend:
int modulo = -72 % 11;
System.out.println("Modulo When Dividend is Negative: " + modulo);
Now use the modulo operator with a positive dividend and a negative divisor:
int modulo1 = 72 % -11;
System.out.println("Modulo When Divisor is Negative: " + modulo1);
Finally, use the modulo operator with a negative dividend and a negative divisor:
int modulo2 = -72 % -11;
System.out.println("Modulo When Both Dividend and Divisor are Negative: " + modulo2);
Complete Code & Output:
Division Vs Modulo: What’s the Difference?
A division operator “/” returns a quotient, while a modulo operator “%” retrieves a remainder in Java:
Consider the following code to understand this difference via Java programming.
Example: Modulo Vs Division in Java
First, use the “%” operator on the given values and store the result in a variable named “modulo”:
int modulo = 73 % 6;
Now use the “/” operator on the same values and store the result in a variable named “division”:
int division = 73 / 6;
Print the output of both operators on the console:
System.out.println("Modulo: " + modulo
+"\nDivision: " + division);
Complete Code & Output:
Possible Exceptions While Working With Modulo Operator
An “ArithmeticException” occurs when a user specifies “0” as a divisor:
Note: The Modulo operator works perfectly fine on Integers, however, it might lead to unexpected results in the case of non-integers.
Modulo Operator Alternatives
The below-listed alternative approaches can help us achieve the same functionality as the Modulo operator in Java:
- Using remainder()
- Using Math.floorMod()
- Using Custom Logic
Alternative 1: Using remainder()
The remainder() method belongs to Java’s BigDecimal class. It computes the remainder of two BigDecimal values. To use this method first import the BigDecimal class in your program:
import java.math.BigDecimal;
Now create a couple of BigDecimal variables to initialize the dividend and divisor:
BigDecimal dividend = new BigDecimal("112.50");
BigDecimal divisor = new BigDecimal("12.2");
Use the remainder() method on the given values to find the remainder. After that, use the println() method to display the remainder on the console:
BigDecimal modulo = dividend.remainder(divisor);
System.out.println("Remainder: "+ modulo);
Complete Code & Output:
Alternative 2: Using Math.floorMod()
The floorMod() is an inbuilt method of the Java Math class. It accepts two integer-type values, performs division, and retrieves the remainder of given numbers. To use this method, first, declare and initialize a couple of integer variables:
int dividend = 125, divisor = 2;
Now use the Math.floorMod() method to get the remainder of input values:
System.out.println("The Remainder: " + Math.floorMod(dividend, divisor));
Complete Code & Output:
Alternative 3: Using Custom Logic
Users can find the remainder of given numbers without using the modulo operator or any built-in methods. To do this, first, create a user-defined function, let’s say “modulo()”. The function accepts two integer-type parameters: “dividend” and “divisor”. Perform the division on the dividend and divisor, and multiply the result with the divisor. After this, subtract the resultant value from the dividend and return the final result:
public static int modulo(int dividend, int divisor)
{
return (dividend - divisor * (dividend/divisor));
}
Now in the main() method, invoke the modulo() function with the desired arguments, and print the result on the console using println():
System.out.println("The Remainder: " + modulo(172, 12));
Complete Code & Output:
This sums up the working of Java’s Modulo operator.
Final Thoughts
Modulo, Modulus, or “%” is an arithmetic operator in Java that performs division on the provided numbers and retrieves the remainder as output. It has numerous use cases, such as checking if the given number is even or odd, finding the next or previous index of circular arrays, converting minutes to hours, and many more. This post has discussed ten different use cases of the Modulo operator, the difference between division and modulo, and some suitable alternatives of the Modulo operator.