Java bitwise AND to check a given number is odd or even

Let’s learn java bitwise AND to check a given number is odd or even.

Java bitwise AND to check a given number is odd or even

Java program to check number is even or odd by using “&” operator is one of the common interview question.

Basically to check if number is even we divide it by 2 and its remainder will be 0. Meanwhile to check if number is odd its remainder will be 1 when divided by 2.

java bitwise AND to check a given number is odd or even

Bitwise AND (&) operator returns bit by bit AND of input values. Here we have to check if last bit is 1.

If last bit is 1 then it is odd else it is even. Also integer numbers are represented as 2’s complement.

Also read – even odd program in java using method

For even number it has 0 as there Least Significant Bit (LSB). Let’s learn to find number even odd using bitwise operator in java,

import java.util.*;
 
public class EvenOddBitwise
{
   static int checkEven(int num) 
   {
      //  if we perform bitwise AND between 1 and "num" result will be 0
      return(num & 1); 
   }
   public static void main(String[] args) 
   {
      int number = 501;
      if(checkEven(number) == 0)
      {
         System.out.print("Even number");
      }
      else
      {
         System.out.print("Odd number");
      }
   }
}



Output:

Odd number

Meanwhile we can also check if number is even or odd using division operator ( / ).

Here division operator basically returns quotient. For example, if we take a number and divide by two and multiply result with 2 then the number will be less in case of odd number and equal in case of even number.

int result = number / 2;
if(result * 2 == number)
{
   System.out.println("Even number");           
}