What is Modulo Operator in Java: Explanation and Examples
modulo operator (%) returns the remainder after dividing one number by another. It is used to find what is left over when one number is divided by another.How It Works
The modulo operator (%) in Java works like this: when you divide one number by another, it gives you the remainder left after the division. Imagine you have 10 cookies and want to share them equally among 3 friends. Each friend gets 3 cookies, and 1 cookie is left over. That leftover cookie is what the modulo operator gives you.
In simple terms, a % b means divide a by b, then return the remainder. It’s like counting how many times one number fits into another and then seeing what is left.
Example
This example shows how to use the modulo operator to find the remainder of dividing 10 by 3.
public class ModuloExample { public static void main(String[] args) { int a = 10; int b = 3; int remainder = a % b; System.out.println("The remainder of " + a + " % " + b + " is " + remainder); } }
When to Use
The modulo operator is useful when you need to find out if a number is divisible by another, or when you want to cycle through a set of values repeatedly. For example, you can use it to check if a number is even or odd by checking number % 2. If the result is 0, the number is even; if 1, it is odd.
It is also helpful in programming tasks like wrapping around array indexes, creating repeating patterns, or working with time calculations like hours and minutes.
Key Points
- The modulo operator (%) returns the remainder of division.
- It works with integers and can also be used with floating-point numbers.
- Commonly used to check divisibility and cycle through values.
- In Java, it follows the sign of the dividend (the first number).