The Wayback Machine - https://web.archive.org/web/20240907060356/https://www.geeksforgeeks.org/java-program-to-check-if-a-given-integer-is-odd-or-even/
Open In App

Java Program to Check if a Given Integer is Odd or Even

Last Updated : 22 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A number that is divisible by 2 and generates a remainder of 0 is called an even number. All the numbers ending with 0, 2, 4, 6, and 8 are even numbers. On the other hand, number that is not divisible by 2 and generates a remainder of 1 is called an odd number. All the numbers ending with 1, 3, 5,7, and 9 are odd numbers. Do refer to the below illustration to get what is supposed to be conveyed out basics here via generic Illustration for any random integer, check whether it is even or odd. 

Input : 13
Output: ODD
Input : 24
Output: EVEN

Methods:

There are various ways to check whether the given number is odd or even. Some of them are as follows starting from the brute force approach ending up at the most optimal approach.

  1. Using Brute Force- Naive Approach
  2. Using bitwise operators
    • Using Bitwise OR
    • Using Bitwise AND
    • Using Bitwise XOR
  3. By Checking the Least Significant Bit

Method 1: Brute Force Naive Approach

It is to check the remainder after dividing by 2. Numbers that are divisible by 2 are even else odd.

Example

Java




// Java Program to Check if Given Integer is Odd or Even
// Using Brute Forcew Approach
 
// Importing required classes
import java.io.*;
import java.util.Scanner;
 
// Main class
class GFG {
 
    // Main Driver Method
    public static void main(String[] args)
    {
        // Declaring and initializing integer variable
        int num = 10;
 
        // Checking if number is even or odd number
        // via remainder
        if (num % 2 == 0) {
 
            // If remainder is zero then this number is even
            System.out.println("Entered Number is Even");
        }
 
        else {
 
            // If remainder is not zero then this number is
            // odd
            System.out.println("Entered Number is Odd");
        }
    }
}


Output

Entered Number is Even

Time Complexity: O(1)

Auxiliary Space: O(1)

Now let us dwell on optimal approaches as follows below as follows with help of bitwise operators

Method 2: Using bitwise operators

  • Bitwise OR
  • Bitwise AND or Bitwise XOR

2-A: Using Bitwise OR

Bitwise OR operation of the even number by 1 increment the value of the number by 1 otherwise it remains unchanged.

Illustration: Bitwise OR 

    Number = 12              1  1  0  0    - Representation of 12 in Binary Format
                Bitwise OR   0  0  0  1    - Representation of  1 in Binary Format
                            
                             1  1  0  1    - Representation of 13 in Binary Format
    Result- Number was even so bitwise Or by 1 increment the value by 1
    Number = 15            1  1  1  1    - Representation of 15 in Binary Format
               Bitwise OR  0  0  0  1    - Representation of  1 in Binary Format
                        
                           1  1  1  1    - Representation of 15 in Binary Format
    Result- Number was odd so bitwise Or by 1 doesn't increment the value by 1

Example

Java




// Java Program to Check if Given Integer is Odd or Even
// Using Bitwise OR
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing integer variable
        // to be checked
        int n = 100;
 
        // Condition check
        // if n|1 if greater than n then this number is even
        if ((n | 1) > n) {
 
            // Print statement
            System.out.println("Number is Even");
        }
        else {
 
            // Print statement
            System.out.println("Number is Odd");
        }
    }
}


Output

Number is Even

Time Complexity: O(1)

Auxiliary Space: O(1)

2-B: Using Bitwise AND

Bitwise AND operation of the odd number by 1 will be 1 because the last bit will be already set otherwise it will give 0. 

Illustration: Bitwise AND 

    Number = 5              0  1  0  1    - Representation of  5 in Binary Format
               Bitwise AND  0  0  0  1    - Representation of  1 in Binary Format
                          
                            0  0  0  1    - Representation of  1 in Binary Format
    Result- Number was odd so bitwise And by 1 is 1
        Number = 8            1  0  0  0    - Representation of  8 in Binary Format
             Bitwise AND  0  0  0  1    - Representation of  1 in Binary Format
                       
                          0  0  0  0    - Representation of  0 in Binary Format
    Result- Number was even so bitwise And by 1 is 0

Example

Java




// Java Program to Check if Given Integer is Odd or Even
// Using Bitwise AND
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declare and initializing integer variable
        int n = 91;
 
        // Condition Check
        // Bitwise AND of any odd number by 1 gives 1
        if ((n & 1) == 1) {
 
            // Print statement
            System.out.println("Number is Odd");
        }
        else {
 
            // Print statement
            System.out.println("Number is Even");
        }
    }
}


Output

Number is Odd

Time Complexity: O(1)

Auxiliary Space: O(1)

 2-C: Using Bitwise XOR

Bitwise XOR operation of the even number by 1 increment the value of the number by 1 otherwise it decrements the value of the number by 1 if the value is odd. It is the most optimal approach.

Illustration: Bitwise XOR  

    Number = 5              0  1  0  1    - Representation of  5 in Binary Format
               Bitwise XOR  0  0  0  1    - Representation of  1 in Binary Format
                       
                            0  1  0  0    - Representation of  4 in Binary Format
    Result- Number was odd so bitwise And by 1 decrement the value
    Number = 8            1  0  0  0    - Representation of  8 in Binary Format
             Bitwise XOR  0  0  0  1    - Representation of  1 in Binary Format

                          1  0  0  1    - Representation of  9 in Binary Format
    Result- Number was even so bitwise And by 1 increment the value

Example

Java




// Java Program to Check if Given Integer is Odd or Even
// Using Bitwise XOR
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declare and initializing integer variable
        int num = 99;
 
        // Condition Check
        // if number^1 increments by 1 then its even number,
        // else odd
        if ((num ^ 1) == num + 1) {
 
            // Print statement
            System.out.println("Number is Even");
        }
        else {
 
            // Print statement
            System.out.println("Number is Odd");
        }
    }
}


Output

Number is Odd

Time Complexity: O(1)

Auxiliary Space: O(1)

 Method 3: Checking the LSB of the Number

The LSB(Least Significant Bit) of an even number is always 0 and that of an odd number is always 1.

Example 

Java




// Java Program to Check if Given Integer is Odd or Even
// by checking the LSB of the Number
 
// Importing required classes
import java.util.*;
 
// Main class
// TestEvenOddByCheckingLSB
public class GFG {
 
    // Method 1
    // To test number is even or odd
    public static String testOddEvenByCheckingLSB(int a)
    {
 
        if (a != 0) {
            if (Integer.toBinaryString(a).endsWith("0")) {
                return "Even";
            }
            else {
                return "Odd";
            }
        }
 
        // Here we will land if
        // it does not ends with 0
        else {
            return "Zero";
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Iterationg over using for loop
        for (int i = 0; i <= 10; i++) {
 
            // Calling the function and printing
            // corresponding number is even or odd
            System.out.println(
                i + " : " + testOddEvenByCheckingLSB(i));
        }
    }
}


Output

0 : Zero
1 : Odd
2 : Even
3 : Odd
4 : Even
5 : Odd
6 : Even
7 : Odd
8 : Even
9 : Odd
10 : Even

Time Complexity: O(1)

Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Sum of Array Divisible by Size with Even and Odd Numbers at Odd and Even Index in Java
Given an array arr[] of size N, Convert the given array as even numbers in the array occurs at the odd index, odd numbers in the array occur at the even index, and whether the sum of the numbers in an array is divisible by the size of an array. If the array follows all the properties then an array is valid else it is invalid. An array will be valid
3 min read
Java Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1-&gt;2-&gt;3-&gt;4-&gt;NULL Output : Even Input : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL Output : OddRecommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1: Count the codes linea
3 min read
Java Program to Check if count of divisors is even or odd
Given a number "n", find its total number of divisors is even or odd. Examples: Input: n = 10 Output: EvenInput: n = 100Output: OddInput: n = 125Output: EvenA naive approach would be to find all the divisors and then see if the total number of divisors is even or odd. The time complexity for such a solution would be O(sqrt(n)) [GFGTABS] Java // Nai
4 min read
Java Program to Convert Integer List to Integer Array
There are many ways to convert integer List to ArrayList where in this article we will be discussing out 2 approaches as below: Using concept od streams in Java8Using Apache Commons LangUsing Guava Library Method 1: Using concept od streams in Java8 So, first, we will get to know about how to convert integer list to array list using java 8. In java
3 min read
Program to Convert Set of Integer to Array of Integer in Java
Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to Se
2 min read
Java Program to Check if a Given Integer is Positive or Negative
Here, the task is to check whether the given integer number is positive or negative. Below are some basic properties of a number. If the Integer is greater than zero then it is a positive integer.If the number is less than zero then it is a negative integer.If the number is equal to zero then it is neither negative nor positive.Input: X = 12 Output
4 min read
Java Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read
Java Program to Find the Frequency of Odd &amp; Even Numbers in the Matrix
Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in th
3 min read
Java Program to Store Even & Odd Elements of an Array into Separate Arrays
Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after
2 min read
Java Program to Find the Sum of First N Odd &amp; Even Numbers
When any number which ends with 0,2,4,6,8 is divided by 2 that is an even number. And when any number ends with 1,3,5,7,9 is not divided by two is an odd number. Example: Input : 8 Output: Sum of First 8 Even numbers = 72 Sum of First 8 Odd numbers = 64Approach #1: Iterative Create two variables evenSum and oddSum and initialize them by 0.Start For
3 min read
Java Program to Calculate the Difference Between the Sum of the Odd Level and the Even Level Nodes of a Binary Tree
Graph Traversal using DFS is an obvious way to traverse a tree with recursion. Below is an algorithm for traversing binary tree using DFS. Prerequisites Graph Traversal using DFSJava Basics(Array List)Recursion Basics Algorithm Initialize the current node as root node and the parent as -1.Traverse the Binary Tree as the in the general DFS fashion a
2 min read
Java Program to Rearrange array elements into alternate even-odd sequence by anticlockwise rotation of digits
Given an array arr[] consisting of N positive integers, the task is to rotate the digits of array elements in an anti-clockwise direction such that elements of the array elements are in alternate even-odd or odd-even form. If multiple solutions exists, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = { 143, 251, 534, 232, 8
4 min read
Java Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Java Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Java Program for Frequencies of even and odd numbers in a matrix
Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in matrix Examples: Input : m = 3, n = 3 { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } Output : Frequency of odd number = 5 Frequency of even number = 4 Input : m = 3, n = 3 { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } Output : Frequency of odd number = 4 Frequency
3 min read
Java Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
8 min read
Java Program for Difference between sums of odd and even digits
Write a java program for a given long integer, the task is to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit). Examples: Input : 1212112Output : YesExplanation:the odd position element is 2+2+1=5the even position element is 1+1+1+2=5the difference is 5-
2 min read
Java Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1-&gt;2-&gt;3-&gt;4 Output: 1-&gt;3-&gt;2-&gt;4 Input: 10-&gt;22-&gt;30-&gt;43-&gt;56-&gt;70 Output: 10-&gt;30-&gt;56-&gt;22-&gt;43-&gt;70Recommended: Please solve it on "PRACTICE" first, before moving on to the
3 min read
Java Program For Segregating Even And Odd Nodes In A Linked List
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.Examples: Input: 17-&gt;15-&gt;8-&gt;12-&gt;10-&gt;5-&gt;4-&gt;1-&gt;7-&gt;6-&gt;NULL Output: 8-&gt;12-&gt;10-&gt;4-&gt;6-&gt;17-&gt;1
6 min read
Integer.MAX_VALUE and Integer.MIN_VALUE in Java with Examples
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, Java has constants to represent these numbers, so that these can be directly assigned to the variable without actuall
3 min read
Converting Integer-String HashMap to String-Array-Integer HashMap in Java
Efficient Conversion of a HashMap&lt;Integer, String&gt; into another HashMap&lt;String, Integer[]&gt; involves organizing integer keys based on their corresponding string values. Here's a concise and efficient Java method to accomplish this transformation, focusing on clear and straightforward implementation. Step-by-Step Implementation of Convers
3 min read
Check if a given string is a valid number (Integer or Floating Point) in Java
In the article Check if a given string is a valid number, we have discussed general approach to check whether a string is a valid number or not. In Java we can use Wrapper classes parse() methods along with try-catch blocks to check for a number. For integer number Integer class provides a static method parseInt() which will throw NumberFormatExcep
4 min read
Print even and odd numbers in increasing order using two threads in Java
Given an integer N, the task is to write Java Program to print the first N natural numbers in increasing order using two threads. Prerequisite: MultithreadingExamples: Input: N = 10Output: 1 2 3 4 5 6 7 8 9 10 Input: N = 18Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Approach: The idea is to create two threads and print even numbers with on
3 min read
Integer.valueOf() vs Integer.parseInt() with Examples
Integer.parseInt():While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt(). This method belongs to Integer class in java.lang package. It takes a valid string as a parameter and parses it into primitive d
4 min read
Java Program to Print a Square Pattern for given integer
Write a java program to print the given Square Pattern on taking an integer as input from commandline. Examples: Input : 3 Output :1 2 3. 7 8 9 4 5 6 Input :4 Output :1 2 3 4 9 10 11 12 13 14 15 16 5 6 7 8 Java Code // Java program to print a square pattern with command // line one argument import java.util.*; import java.lang.*; public class Squar
2 min read
Java Program to Extract Digits from A Given Integer
Problem Statement: For any random number taken into consideration the goal is to access every digit of the number. Illustration: Simply taking two numbers be it, 12345 and 110102 absolutely random pick over which computation takes place as illustrated: Input: 12345 Output: 1 // 1 digit 2 // Digit next to 1st digit 3 4 5 // Last Digit of the number
3 min read
Java Program to Increment by 1 to all the Digits of a given Integer
Given an integer, the task is to generate a Java Program to Increment by 1 All the Digits of a given Integer. Examples: Input: 12345 Output: 23456 Input: 110102 Output: 221213 Approach 1: In this approach, we will create a number which will be of the same length as the input and will contain only 1 in it. Then we will add them. Take the integer inp
2 min read
Java Program for Number of elements with odd factors in given range
Given a range [n, m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output : 150 A Simple Solution is to loop through all numb
3 min read
Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples: Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6,
5 min read
Sort all even numbers in the Array without changing order of odd elements
Given an array arr[] of size N, the task is to sort all the even numbers in the array, without changing the order of odd elementsExamples: Input: arr[] = {4, 7, 2, 11, 15}Output: {2, 7, 4, 11, 15}Explanation: Even numbers are sorted at their corresponding places, without changing the order of odd elements Input: arr[] = {12, 6}Output: {6, 12} Appro
4 min read
Article Tags :
Practice Tags :