How to check if a number is even
Short answer
A number is even if the remainder of dividing it by 2 is zero:
void main() {
int number = 14;
IO.println(number % 2 == 0);
}Output:
trueA method
Move the check into a method and apply it to several numbers:
boolean isEven(int n) {
return n % 2 == 0;
}
void main() {
for (int n : new int[] {3, 8, 0, -4}) {
IO.println(n + " " + (isEven(n) ? "even" : "odd"));
}
}Output:
3 odd
8 even
0 even
-4 evenFiltering even numbers
In a stream the check becomes a filter() condition:
void main() {
var evens = IntStream.rangeClosed(1, 10).filter(n -> n % 2 == 0).boxed().toList();
IO.println(evens);
}Output:
[2, 4, 6, 8, 10]Common mistake
Checking for odd numbers with n % 2 == 1. For negative numbers the remainder is negative, and the check fails:
void main() {
int n = -3;
IO.println(n % 2);
IO.println(n % 2 == 1);
IO.println(n % 2 != 0);
}Output:
-1
false
trueWrite n % 2 != 0 or Math.floorMod(n, 2) == 1.
Functions used in this recipe
- % — Returns the remainder of a division.
- Math.floorMod() — A remainder that always has the sign of the divisor.