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.
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.
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
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.
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
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.