The modulo operator (%) in Java is an arithmetic operator used to find the remainder after division of one number by another. It is commonly used in mathematical calculations, loops, condition checking, and number-based logic.
class Test {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println(a % b);
}
}
Output
1
Explanation: 10 ÷ 3 = 3 with a remainder of 1.
Syntax:
A % B
Where A is the dividend and B is divisor
Example 1: Modulo with Negative Numbers
class Example {
public static void main(String[] args) {
System.out.println(10 % 3);
System.out.println(-10 % 3);
System.out.println(10 % -3);
System.out.println(-10 % -3);
}
}
Output
1 -1 1 -1
Explanation:
- The sign of the result depends on the dividend.
- Divisor’s sign does not affect the sign of the remainder.
Example 2: Modulo with Floating-Point Numbers
class FloatModulo {
public static void main(String[] args) {
double x = 10.5, y = 3.2;
System.out.println(x % y);
}
}
Output
0.8999999999999995
Explanation: Java allows % with floating-point values, though results may show precision issues due to binary representation.
Note:
- Division by zero (a % 0) throws an ArithmeticException.
- % works with int, long, float, and double.
- Modulo is not a percentage operator.
Difference Between Modulo and Division
Operator | Purpose | Result |
|---|---|---|
/ | Quotient | Division result |
% | Remainder | Remaining value |