This post demonstrates how to determine whether a given number is odd or even without using the module operator. The given number is divided by two, with the decimals truncated, and then multiplied by two. If the given number is even, this logic returns the same number; otherwise, it returns a different number.
Java Program
package in.yawin; public class CheckOddOrEven { public static void main(String[] args) { int number = 12; boolean isEven = check(number); if (isEven) { System.out.println("The number " + number + " is even "); } else { System.out.println("The number " + number + " is odd "); } number = 11; isEven = check(number); if (isEven) { System.out.println("The number " + number + " is even "); } else { System.out.println("The number " + number + " is odd "); } } public static boolean check(int number) { return number / 2 * 2 == number; } }
Output
The number 12 is even The number 11 is odd
Explanation
The java programme demonstrates how to determine whether a given number is odd or even without using the java mod operator. When an integer number is divided by 2, the result is also an integer number. The decimal portion will be removed. When an odd number is divided by two, a fraction value is subtracted. There is no fractional value for an even number. If the divided value is multiplied by 2, the result should be the same as given. If the number is an even number, the multiplied value equals the given value. If the number is an odd number, the multiplied value is not the same as the given value. The java programme will determine whether the given value is odd or even without using the java mod operator.