Check whether given number is even or odd

Upasana | May 24, 2019 | 1 min read | 412 views


We can easily find if a number is even or odd in Java using the below method.

Using remainder operation for even odd check
public static boolean isOdd(int i) {
     return i % 2 != 0;
}

Here we are checking if the remainder operation returns a non-zero result when divided by 2.

Generally, the better (and faster) approach is to using AND operator, as shown in below code snippet:

Using AND operator for even/odd check
public static boolean isOdd(int i) {
     return (i & 1) != 0;
}

Here we are checking if the least significant bit (LSB) is zero or not. If it is zero then number is even else number is odd.

What is LSB

LSB, the least significant bit is the lowest bit in a series of numbers in binary; the LSB is located at the far right of a string. For example, in the binary number 10001 (17 in decimal), the least significant bit is the far right 1.

This may not work

As suggested in Puzzle 1: Oddity in Java Puzzler book, the below code will not work for all negative numbers.

This method will fail for all negative odd numbers
public static boolean isOdd(int i) {
    return i % 2 == 1;
}

Reference

  • Java Puzzlers: Traps, Pitfalls, and Corner Cases by Joshua Bloch, Neal Gafter. Puzzle 1: Oddity


Top articles in this category:
  1. Check if the given string is palindrome
  2. Prime number checker in Java
  3. Palindrome checker in Java
  4. Find two numbers of which the product is maximum in an array
  5. Armstrong Number in Java
  6. Java Coding Problems for SDET Automation Engineer
  7. 50 Java Interview Questions for SDET Automation Engineer

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.