%
Returns the remainder of a division.
Available since: Java 1.0
Syntax
a % bExamples
Even check and the last digit:
void main() {
IO.println(17 % 5);
IO.println(10 % 2 == 0 ? "even" : "odd");
IO.println(1234 % 10);
}Output:
2
even
4The result has the sign of the dividend:
void main() {
IO.println(-7 % 3);
IO.println(Math.floorMod(-7, 3));
IO.println(7.5 % 2);
}Output:
-1
2
1.5Notes
For negative numbers % gives a negative remainder, so an odd check is n % 2 != 0, not n % 2 == 1. If you need a result from 0 to b - 1 (for example, weekdays in a circle), use Math.floorMod(). An integer remainder by 0 throws ArithmeticException.
See also
- Math.floorMod() — A remainder that always has the sign of the divisor.
- ++ / -- — Increases or decreases a variable by one.
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.