Odd and Even NumbersDetermine if numbers are odd or even. Use modulo division and handle negative numbers.
This page was last reviewed on May 4, 2023.
Odd, even numbers. All integers have a parity: they are even or odd. Numbers like 1 and 3 are odd, and 0 and 2 are even. This can be computed with a simple Java method.
With a modulo division, we determine if a number evenly divides into another. In this way we tell if a number can be divided by 2 evenly—it is then even.
Warning For negative odd numbers, the remainder will be -1 not 1. So we test for "not equal to zero" instead.
Example program. Let us examine the program. We introduce two static methods, isEven and isOdd. We could implement isOdd by returning "!isEven" but this does not simplify the program.
Info The methods isEven and isOdd return booleans—true or false—based on the parity of the argument int.
public class Program { public static boolean isEven(int value) { // An even number is always evenly divisible by 2. return value % 2 == 0; } public static boolean isOdd(int value) { // This handles negative and positive odd numbers. return value % 2 != 0; } public static void main(String[] args) { // Test our implementation. int value = 100; if (isEven(value)) { System.out.println(value); } value = 99; if (isOdd(value)) { System.out.println(value); } } }
100 99
Negative, odd numbers. Years ago I implemented a flawed isOdd method. It tested for a remainder of 1, so would always return false on negative numbers. This was a negative event in my life.
Here I test the isOdd method for negative odd numbers and it is correct. IsEven does not have a similar issue.
public class Program { public static boolean isOdd(int value) { // Same implementation as above. return value % 2 != 0; } public static void main(String[] args) { // Test positive and negative numbers for odd parity. for (int i = -5; i <= 5; i++) { if (isOdd(i)) { System.out.println(i); } } } }
-5 -3 -1 1 3 5
A summary. For games and simulators, a fast test for a number's parity can be useful. Other programs may also benefit from this code. We implemented and tested odd and even tests.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 4, 2023 (edit).
© 2007-2023 Sam Allen.