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
Approaches to Check Odd or Even
There are multiple ways to determine whether a number is odd or even. These approaches range from simple arithmetic to bitwise operations.
Method 1: Using Modulus Operator (Naive & Most Readable)
If a number gives remainder 0 when divided by 2, it is even; otherwise, odd.
class GFG {
public static void main(String[] args) {
int num = 10;
if (num % 2 == 0) {
System.out.println("Entered Number is Even");
} else {
System.out.println("Entered Number is Odd");
}
}
}
Output
Entered Number is Even
Method 2: Using Bitwise Operators (Optimized)
Bitwise methods work by analyzing the Least Significant Bit (LSB) of a number.
Method 2A: Using Bitwise OR (|)
If (n | 1) is greater than n, then n is even. Otherwise, n is odd.
class GFG {
public static void main(String[] args) {
int n = 100;
if ((n | 1) > n) {
System.out.println("Number is Even");
} else {
System.out.println("Number is Odd");
}
}
}
Output
Number is Even
Method 2B: Using Bitwise AND (&) Best Bitwise Approach
- Odd numbers have LSB = 1
- Even numbers have LSB = 0
class GFG {
public static void main(String[] args) {
int n = 91;
if ((n & 1) == 1) {
System.out.println("Number is Odd");
} else {
System.out.println("Number is Even");
}
}
}
Output
Number is Odd
Method 2C: Using Bitwise XOR (^)
If (n ^ 1) == n + 1, number is even. Otherwise, odd.
class GFG {
public static void main(String[] args) {
int num = 99;
if ((num ^ 1) == num + 1) {
System.out.println("Number is Even");
} else {
System.out.println("Number is Odd");
}
}
}
Output
Number is Odd
Method 3: Checking the Least Significant Bit (Modernized)
The LSB(Least Significant Bit) of an even number is always 0 and that of an odd number is always 1.
class GFG {
static String checkOddEven(int n) {
if (n == 0) return "Zero";
return ((n & 1) == 0) ? "Even" : "Odd";
}
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
System.out.println(i + " : " + checkOddEven(i));
}
}
}
Output
0 : Zero 1 : Odd 2 : Even 3 : Odd 4 : Even 5 : Odd 6 : Even 7 : Odd 8 : Even 9 : Odd 10 : Even