public static boolean isOdd(int i) {
return i % 2 != 0;
}
Check whether given number is even or odd
Carvia Tech | 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.
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:
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.
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
- Check a number is Prime: Java Coding Problem
- Palindrome checker in Java
- Armstrong Number in Java
- Find two numbers of which the product is maximum in an array
- SDET Java Coding Challenges
- 50 SDET Java Interview Questions & Answers
Find more on this topic:
Subscribe to Interview Questions
Recommended books for interview preparation:
Similar Posts
- Reverse position of words in a string using recursion
- REST Assured with plain/text response body
- Get distinct words from a given file in Java
- SDET Java Coding Challenges
- REST Assured vs Apache HttpClient and RestTemplate
- Java 11 HttpClient with Basic Authentication
- HTTP GET request with Java 11 HttpClient - Kotlin
- HTTP Head request using Java 11 HttpClient - Kotlin
- Using Java 11 HttpClient with Kotlin Coroutines
- Migrating Spring Boot tests from Junit 4 to Junit 5