# 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:

###### Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..