Java Interview Question: Determining Whether an Integer Is Odd – Discussion and Solutions
This article walks through a common Java interview problem of checking if an integer is odd, presenting multiple candidate solutions, explaining their shortcomings, and culminating in an optimal bitwise implementation while also discussing performance misconceptions.
The article introduces a seemingly simple Java interview question: write a method public boolean isOdd(int i) that returns true if the given integer is odd.
Initial candidate answers use System.out.println statements or return statements based on i % 2 == 1 , but they contain compilation errors or verbose logic.
Through a series of interview prompts, candidates are guided to improve the code, handling negative numbers and simplifying the expression to a single return statement:
public boolean isOdd(int i) {
return i % 2 == 1;
}Further discussion explores faster alternatives to the modulo operation, leading to bitwise approaches. One candidate suggests using shift operators, which is not ideal, and finally the optimal solution using a bitwise AND is presented:
public boolean isOdd(int i) {
return (i & 1) == 1;
}The article also notes that, contrary to intuition, the bitwise version does not show a measurable speed advantage over the modulo version in practical tests, prompting a deeper conversation about compiler optimizations and CPU behavior.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.