Title: Count Even Numbers in an Array
In this guide, you will learn how to count the even numbers in an array using Java. Parity counting is one of the smallest useful array problems you can write, and it is a surprisingly good lens into how Java handles the modulo operator for negative values.
We will walk through the problem, build a complete program, trace it on a sample input, and then look at the signed-modulo trap, the “zero is even” question, and the follow-up questions a Java interviewer tends to ask on this problem.
Understanding the Problem
Given an array of n integers, the task is to return how many of them are even. An integer is even when it is divisible by 2 with no remainder. For the input [3, 8, 1, 6, 4, 7, 2], the even values are 8, 6, 4, and 2, so the answer is 4.
Two tiny subtleties hide in the definition. First, 0 is even by convention, and the code should treat it that way without any special case. Second, Java’s % operator preserves the sign of the dividend, so -3 % 2 is -1, not 1. Checking value % 2 == 0 happens to be sign-safe (every even negative gives 0), but the symmetric-looking check value % 2 == 1 for odd values is not.
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 needed.
- For each element
value, test whethervalue % 2 == 0. The== 0comparison is sign-safe and detects every even integer, including0and negative evens. - Increment
countfor every matching element and return it once the loop ends.
Java Program
public class CountEvens {
public static int countEvens(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 evens = countEvens(values);
System.out.println("Even count: " + evens);
}
}Explanation of the Program
The class CountEvens exposes a single static method, countEvens, 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 evens 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. For a positive even value such as 8, 8 % 2 is 0. For a negative even value such as -4, -4 % 2 is also 0, because Java’s % operator truncates toward zero and even negatives divide cleanly. For odd values, the result is 1 for positives and -1 for negatives, so comparing against 0 is the sign-safe way to detect evenness.
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 four even and three odd values, calls countEvens, and prints the result. Running it prints Even count: 4.
Step-by-Step Trace
Let us trace countEvens on the input [7, 4, 2, 9, 6, 1]. The expected final answer is 3, since the even values are 4, 2, and 6.
| Iteration | value | value % 2 | Even? | count (before) | count (after) |
|---|---|---|---|---|---|
| 1 | 7 | 1 | no | 0 | 0 |
| 2 | 4 | 0 | yes | 0 | 1 |
| 3 | 2 | 0 | yes | 1 | 2 |
| 4 | 9 | 1 | no | 2 | 2 |
| 5 | 6 | 0 | yes | 2 | 3 |
| 6 | 1 | 1 | no | 3 | 3 |
At the end of iteration i, count holds the number of even values among numbers[0..i-1]. The invariant is maintained by exactly one branch per iteration: either the increment on the even path, or the no-op fall-through on the odd path.
Examples
Example 1: All even values
Every element passes the parity test, so the count equals the array length.
int[] nums = {2, 4, 6, 8};
int evens = countEvens(nums);
System.out.println(evens);
// Output: 4Example 2: Negative values and zero
Negative evens and the special case of 0 are all counted correctly. The modulo check does not need a sign branch.
int[] nums = {-4, -3, 0, 5, 10};
int evens = countEvens(nums);
System.out.println(evens);
// Evens: -4, 0, 10
// Output: 3Example 3: All odd values
When no element passes the parity test, the count stays at 0.
int[] nums = {1, 3, 5, 7};
int evens = countEvens(nums);
System.out.println(evens);
// Output: 0Common Mistakes to Avoid
The algorithm looks like a one-liner, but Java’s signed modulo and the fencepost between index and value together produce several reliable traps. These are the mistakes learners actually make on this problem.
- Testing
value % 2 == 1for odds – fails on every negative odd value because-3 % 2is-1, not1, so negative odds slip through as if they were even. Usevalue % 2 != 0or(value & 1) == 1instead. - Counting indices instead of values – writing
if (i % 2 == 0)inside an indexed loop counts even-indexed elements, which is a different problem. Test the element at the index, not the index itself. - Treating
0as a separate case – adding|| value == 0to the condition is harmless but a sign of confusion, since0 % 2is already0. Trust the modulo check and leave the extra clause out. - Dividing instead of taking the remainder – typing
value / 2 == 0tests whether the value is0or1, not whether it is even. The operator for parity is%. - Returning on the first odd value – placing a
returninside anelsebranch exits the method as soon as any odd value appears, so the count is almost always wrong. 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 (even or odd)
- All elements even
- All elements odd
- Array containing
0among other values - Negative values mixed with positives
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 0 for even values and 1 for odd 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.MIN_VALUE entry on the edge-case list is worth a sanity check. Integer.MIN_VALUE is -2^31, which is divisible by 2, so Integer.MIN_VALUE % 2 is 0 and the value is correctly counted as even. The same would not be true of Integer.MIN_VALUE‘s absolute value: negating it in int arithmetic overflows back to itself. The modulo check avoids negation entirely, so the overflow does not apply here.
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 evens and odds together in one pass? – track two counters inside the same loop, or return a
(evens, odds)pair; the time stays O(n) and the space stays O(1). - How would you count elements matching an arbitrary predicate? – take an
IntPredicateparameter and callpredicate.test(value)inside the loop; the whole method generalises to any boolean test over anint. - How would you partition the array into evens and odds in-place? – use a two-pointer sweep from both ends, swapping an odd value on the left with an even value on the right until the pointers meet, in O(n) time with O(1) extra space.
- How would you count evens 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 even bits set in a packed bitmap? – mask every other bit with
0x55555555, then useInteger.bitCounton the masked value; the whole thing runs in O(1) per 32-bit word.
Conclusion
Counting the even 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 and reuse it for counting positives, counting 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.



