public static boolean isOdd(int i) {
return i % 2 != 0;
}
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
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.
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:
- Check if the given string is palindrome
- Prime number checker in Java
- Palindrome checker in Java
- Find two numbers of which the product is maximum in an array
- Armstrong Number in Java
- Java Coding Problems for SDET Automation Engineer
- 50 Java Interview Questions for SDET Automation Engineer
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..