Check whether given number is even or odd

Carvia Tech | May 24, 2019 | 1 min read | 12 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. Top 50 SDET Java Programming Interview Questions & Answers
  2. Check if the given number is Armstrong Number in Java
  3. How to check if the given number is palindrome in Java
  4. Check a number is Prime: Java Coding Problem
  5. How to reverse a number in Java
  6. Calculate factorial of a number in Java using recursion
  7. Find two numbers of which the product is maximum in an array



Find more on this topic:
SDET Interviews image
SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info