Java program to find odd or even number

Here we are going to write a Java program to find odd or even number. We can do this in 2 ways:

  1. Divide by 2 and check the remainder (Classic way).
  2. Using bitwise AND (&) operator.

Let’s implement the first way:

Java program to find odd or even number using classical way:

import java.util.Scanner;

class OddOrEven
{
   public static void main(String args[])
   {
      int x;
      System.out.println("Enter an integer to check if it is odd or even ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();

      if ( x % 2 == 0 )
         System.out.println("You entered an even number.");
      else
         System.out.println("You entered an odd number.");
   }
}

 

OUTPUT:

# javac OddOrEven.java
# java OddOrEven
Enter an integer to check if it is odd or even
5
You entered an odd number.

# java OddOrEven
Enter an integer to check if it is odd or even
12
You entered an even number.

 

Java program to find odd or even number using Bitwise AND (&) operator:

import java.util.Scanner;

class OddOrEven
{
   public static void main(String args[])
   {
      int x;
      System.out.println("Enter an integer to check if it is odd or even ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();

      if (n & 1 == 1)
         System.out.println("You entered an odd number.");
      else
         System.out.println("You entered an even number.");
   }
}

Let’s see how it works:

  • Let’s suppose user enters 7, in binary 7 = 0111.
  • Now (n & 1) i.e. 0111 & 0001 = 0001 i.e. equals to 1.
  • Condition becomes True and we get “Odd number” as output.
  • You can check for various number and the conclusion will be:

The least significant bit of every odd number is 1, so ( odd_number & 1 ) will be one always and also ( even_number & 1 ) is zero.

That’s it, comment for any query.

Leave a Comment