Title: Count Odd Numbers in an Array
In this guide, you will learn how to count the odd numbers in an array using Java. The problem is one line of logic on paper, but it hides the single most common Java parity bug: using value % 2 == 1 as the odd check.
We will walk through the problem, build a complete program with a sign-safe parity check, trace it on a sample input, and then look at the Math.abs trap, the bitwise alternative, and the follow-up questions a Java interviewer tends to ask.
Understanding the Problem
Given an array of n integers, the task is to return how many of them are odd. An integer is odd when it leaves a non-zero remainder when divided by 2. For the input [3, 8, 1, 6, 4, 7, 2], the odd values are 3, 1, and 7, so the answer is 3.
The entire problem hinges on one Java-specific detail. The % operator preserves the sign of the dividend, so -3 % 2 is -1, not 1. Writing value % 2 == 1 as the odd check silently drops every negative odd value, because their remainder is -1. The sign-safe check is value % 2 != 0, which correctly says “any non-zero remainder means odd”.
Approach / Algorithm Steps
- Reject the input early if the array is
null, since the count is undefined for a missing reference. An empty array is fine: its count is0. - Declare a counter
countinitialised to0. - Walk the array with an enhanced for loop so no index is tracked.
- For each element
value, test whethervalue % 2 != 0. The non-zero check is sign-safe and catches both positive and negative odd values. - Increment
countfor every matching element and return it once the loop ends.
Java Program
public class CountOdds {
public static int countOdds(int[] numbers) {
if (numbers == null) {
throw new IllegalArgumentException("Array must not be null");
}
int count = 0;
for (int value : numbers) {
if (value % 2 != 0) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int[] values = {3, 8, 1, 6, 4, 7, 2};
int odds = countOdds(values);
System.out.println("Odd count: " + odds);
}
}Explanation of the Program
The class CountOdds exposes a single static method, countOdds, which takes an int[] and returns a plain int. The result cannot exceed numbers.length, which already fits in an int, so no wider return type is needed.
The method validates only against null, not against an empty array. The count of odds in an empty array is a perfectly well-defined 0, so throwing there would punish a reasonable caller. Rejecting null is still worth doing because an unchecked dereference would surface as a NullPointerException on the for line, which gives the caller no useful information about what went wrong.
The loop uses the enhanced for syntax for (int value : numbers) so no index is tracked. For a problem that does not care about position, dropping the index removes a whole class of off-by-one mistakes.
The parity test value % 2 != 0 is the heart of the method, and the choice of operator here is deliberate. For a positive odd value such as 7, 7 % 2 is 1. For a negative odd value such as -3, -3 % 2 is -1, because Java’s % operator keeps the sign of the dividend. Both results are non-zero, so comparing against 0 rather than against 1 catches odd values regardless of sign.
When the test passes, count++ increments the running total. The ++ postfix operator is the idiomatic way to bump a counter by 1, and it is a touch clearer here than count += 1.
The main method is a tiny driver: it builds a sample array that mixes three odd and four even values, calls countOdds, and prints the result. Running it prints Odd count: 3.
Step-by-Step Trace
Let us trace countOdds on the input [5, 2, 7, 4, 1, 8]. The expected final answer is 3, since the odd values are 5, 7, and 1.
| Iteration | value | value % 2 | Odd? | count (before) | count (after) |
|---|---|---|---|---|---|
| 1 | 5 | 1 | yes | 0 | 1 |
| 2 | 2 | 0 | no | 1 | 1 |
| 3 | 7 | 1 | yes | 1 | 2 |
| 4 | 4 | 0 | no | 2 | 2 |
| 5 | 1 | 1 | yes | 2 | 3 |
| 6 | 8 | 0 | no | 3 | 3 |
At the end of iteration i, count holds the number of odd values among numbers[0..i-1]. The invariant is maintained by exactly one branch per iteration: the increment on the odd path, or the no-op fall-through on the even path.
Examples
Example 1: All odd values
Every element passes the parity test, so the count equals the array length.
int[] nums = {1, 3, 5, 7, 9};
int odds = countOdds(nums);
System.out.println(odds);
// Output: 5Example 2: Negative odd values
Negative odds are counted correctly thanks to the != 0 check. The naive == 1 check would miss them silently.
int[] nums = {-7, -4, -1, 0, 3};
int odds = countOdds(nums);
System.out.println(odds);
// Odds: -7, -1, 3
// Output: 3Example 3: All even values including zero
When no element passes the parity test, the count stays at 0. The special case of 0 is handled by the modulo check without a separate branch, since 0 % 2 is 0.
int[] nums = {0, 2, 4, 6};
int odds = countOdds(nums);
System.out.println(odds);
// Output: 0Common Mistakes to Avoid
The algorithm looks like a one-liner, but the signed-modulo rule and a tempting Math.abs shortcut together produce several reliable traps. These are the mistakes learners actually make on this problem.
- Testing
value % 2 == 1– silently drops every negative odd value because-3 % 2is-1, not1. On an input like[-1, -3, -5]the count comes out as0instead of3. Usevalue % 2 != 0or(value & 1) != 0instead. - Reaching for
Math.abs(value) % 2 == 1– looks like it fixes the sign problem but misses a subtler issue:Math.abs(Integer.MIN_VALUE)returnsInteger.MIN_VALUEitself because the positive counterpart does not fit in anint. The sign-safe modulo or bitwise checks need no absolute value at all. - Writing
value % 2 == -1to catch negative odds – asymmetric and brittle, since the same code then fails for positive odd values. Compare against0with!=so both signs are handled by one branch. - Counting indices instead of values – writing
if (i % 2 != 0)inside an indexed loop counts odd-indexed elements, which is a different problem. Test the element at the index, not the index itself. - Returning on the first odd value – placing a
returninside theifbody exits the method as soon as any odd value appears, so the count degenerates to0or1. Onlyreturn count;after the loop completes.
Edge Cases to Test
Walk through this checklist before you call the solution done. The first few are the ones an interviewer is most likely to probe.
- Empty array (count is
0) - Null array reference
- Single-element array (odd or even)
- All elements odd
- All elements even
- Negative odd values (the signed-modulo trap)
Integer.MAX_VALUEpresent (it is odd, since it is2^31 - 1)Integer.MIN_VALUEpresent (it is even, since it is-2^31)
Additional Considerations
The algorithm runs in O(n) time, since every element is visited exactly once, and there is no way to do better because any element can tip the count. The space complexity is O(1), because only the counter and the loop variable are allocated regardless of the input size.
A bitwise alternative to value % 2 != 0 is (value & 1) != 0. The least significant bit of a two’s-complement integer is 1 for odd values and 0 for even values, regardless of sign, so the bitwise form sidesteps the signed-modulo question entirely. On modern JVMs the compiler already lowers both expressions to the same machine code, so the choice is purely about readability.
The Integer.MAX_VALUE and Integer.MIN_VALUE pair on the edge-case list reinforces the mental model. Integer.MAX_VALUE is 2147483647 = 2^31 - 1, which is odd; Integer.MIN_VALUE is -2147483648 = -2^31, which is even. Both values survive the parity check without any special handling, which is the real payoff of the sign-safe comparison.
Interview Follow-up Questions
The base problem is only the opening move. A real interviewer will push with questions like these, each probing a different axis of the solution.
- Can you count odds and evens together in one pass? – track two counters inside the same loop, or return a
(odds, evens)pair; the time stays O(n) and the space stays O(1). - How would you count only the odd values that are also strictly positive? – add
&& value > 0to the condition; the short-circuit evaluation means the extra test runs only when the parity test already passes. - How would you return the indices of odd values instead of just the count? – make two passes: the first counts to size the result array exactly, the second fills it with the matching indices; alternatively build an
ArrayList<Integer>in one pass and convert at the end. - How would you count odds in a very large array in parallel? – use
Arrays.stream(numbers).parallel().filter(v -> (v & 1) != 0).count(), which splits the array into chunks, counts each chunk independently, and sums the chunk counts. - How would you count the number of odd bits set in a packed bitmap? – mask every other bit with
0xAAAAAAAA, then useInteger.bitCounton the masked value; the whole thing runs in O(1) per 32-bit word.
Conclusion
Counting the odd numbers in an array in Java is a one-pass loop built around a single parity test, with two decisions tucked inside it: validate against null but accept an empty array (whose count is a perfectly honest 0), and prefer value % 2 != 0 or (value & 1) != 0 over the sign-fragile value % 2 == 1. Once those two habits are in place, the same shape of code generalises to any predicate count, to parallel streams, and to packed-bitmap variants at scale.
Try adapting the code above to accept an IntPredicate parameter so the same method can count odds, positives, multiples of three, or any other condition. The whole method becomes a tiny general-purpose counter.
You can learn more Array problems like this one here: Arrays.



