Â

**Odd or Even checking using bitwise AND operator**

Â

Another way to solve this problem without using modulus operator is, by using bitwise AND operator. Since integer numbers are represented as 2's complement and even number has 0 as there LSB, if we perform a bitwise AND between 1 and number, result will be zero. This would be enough to check if a number is even or odd in Java.

if((number & 1) == 0){

Â Â System.out.println("Even number");

}

Â

Here is complete Java program to test if number is even or odd without using modulus operator . This program uses both the approach e.g. using division and bitwise operator to identify if a number is odd or even.

/**

Â * Java program to check if a number is even or odd without using modulus or remainder

Â * operator. This examples uses bitwise AND and division operator to check evenness.

Â *

Â * @author Javin Paul

Â */

public class EvenOrOdd {

Â

Â Â public static void main(String args[]) {

Â Â Â

Â Â Â Â //Testing, let's test both methods for positive and negative integers Â Â Â Â

Â Â Â Â System.out.println("Checking if a number is even or odd using division and bitwise operator");

Â Â Â Â for(int i= -1; i<2; i++){

Â Â Â Â Â Â isEvenOrOdd(i); //calling division operator method

Â Â Â Â Â Â isOddOrEven(i); //calling

Â Â Â Â } Â Â Â Â

Â Â Â Â

Â Â } Â Â

Â Â Â Â

Â Â /*

Â Â Â * checking even and odd number without using modulus or remainder operator, Instead

Â Â Â * this method uses division operator.

Â Â Â */

Â Â public static void isEvenOrOdd(int number){

Â Â Â Â int quotient = number/2;

Â Â Â Â

Â Â Â Â if(quotient*2== number){

Â Â Â Â Â Â System.out.println("Using division operator: " Â + number + " is Even number");

Â Â Â Â Â Â

Â Â Â Â }else{

Â Â Â Â Â Â System.out.println("Using division operator: " Â + number Â + " is Odd number");

Â Â Â Â }

Â Â }

Â Â

Â Â /*

Â Â Â * This method uses bitwise AND (&) operator to check if a number is

Â Â Â * even or odd in Java

Â Â Â */

Â Â public static void isOddOrEven(int number){

Â Â Â Â if((number & 1) == 0){

Â Â Â Â Â Â System.out.println("Using bitwise operator: " Â + number Â + " is Even number");

Â Â Â Â }else{

Â Â Â Â Â Â System.out.println("Using bitwise operator: " Â + number Â + " is Odd number");

Â Â Â Â }

Â Â } Â

Â Â

}

Â

Output:

Checking if a number is even or odd using division and bitwise operator

Using division operator: -1 is Odd number

Using bitwise operator: -1 is Odd number

Using division operator: 0 is Even number

Using bitwise operator: 0 is Even number

Using division operator: 1 is Odd number

Using bitwise operator: 1 is Odd number

Â