Title: Count Zero Elements in an Array
In this guide, you will learn how to count the zero elements in an array using Java. The problem looks like a one-liner, and on an int[] it genuinely is, but the same idea opens the door to classics like “move zeroes to the end” and a surprisingly subtle floating-point question for double[].
We will walk through the problem, build a complete program, trace it on a sample input, and then look at the equality check versus the assignment typo, the boxed-Integer wrinkle, 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 equal to 0. For the input [3, 0, -1, 0, 7, 0, 4], the three 0 entries make the answer 3.
The definition is as crisp as it gets: a value is “zero” when it compares equal to the integer constant 0. There is no sign subtlety for int, no modulo question, and nothing to interpret. The only Java detail that could bite is accidentally writing = (assignment) instead of == (equality) inside the if condition.
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 == 0. - Increment
countfor every matching element and return it once the loop ends.
Java Program
public class CountZeros {
public static int countZeros(int[] numbers) {
if (numbers == null) {
throw new IllegalArgumentException("Array must not be null");
}
int count = 0;
for (int value : numbers) {
if (value == 0) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int[] values = {3, 0, -1, 0, 7, 0, 4};
int zeros = countZeros(values);
System.out.println("Zero count: " + zeros);
}
}Explanation of the Program
The class CountZeros exposes a single static method, countZeros, 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 zeros 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 test value == 0 is the heart of the method. For a primitive int, == is a simple numeric equality: the bit pattern of value is compared against the bit pattern of the constant 0, with no auto-unboxing and no reference check. Watch the operator carefully, since a stray = would make the condition an assignment that always evaluates to the right-hand side.
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 with three 0 values among four non-zero values, calls countZeros, and prints the result. Running it prints Zero count: 3.
Step-by-Step Trace
Let us trace countZeros on the input [5, 0, -2, 0, 3, 0]. The expected final answer is 3, since 0 appears three times.
| Iteration | value | value == 0? | count (before) | count (after) |
|---|---|---|---|---|
| 1 | 5 | no | 0 | 0 |
| 2 | 0 | yes | 0 | 1 |
| 3 | -2 | no | 1 | 1 |
| 4 | 0 | yes | 1 | 2 |
| 5 | 3 | no | 2 | 2 |
| 6 | 0 | yes | 2 | 3 |
At the end of iteration i, count holds the number of zero values among numbers[0..i-1]. The invariant is maintained by exactly one branch per iteration: the increment on the zero path, or the no-op fall-through on the non-zero path.
Examples
Example 1: Zeros interleaved with non-zeros
A straightforward input with zeros scattered between other values.
int[] nums = {1, 0, 2, 0, 3};
int zeros = countZeros(nums);
System.out.println(zeros);
// Output: 2Example 2: No zeros
When no element matches, the count stays at 0.
int[] nums = {1, 2, 3, 4};
int zeros = countZeros(nums);
System.out.println(zeros);
// Output: 0Example 3: All zeros
Every element matches, so the count equals the array length. The default value of every int[] element in Java is already 0, so new int[3] would behave the same way as the literal below.
int[] nums = {0, 0, 0};
int zeros = countZeros(nums);
System.out.println(zeros);
// Output: 3Common Mistakes to Avoid
The algorithm looks like a one-liner, but a few Java quirks around equality and boxing still catch learners. These are the mistakes you actually see on this problem.
- Typing
=instead of==–if (value = 0)is a compile error in Java (the condition is notboolean), which is a gift compared to C, but on abooleanfield the same typo compiles and silently rewrites the value. Reread the condition and make sure it is a comparison. - Expecting falsy semantics – writing
if (!value)to test “is zero” works in languages such as C and JavaScript but not in Java, where!requires abooleanoperand. Use the explicitvalue == 0. - Comparing boxed
Integerwith==– on a primitiveintthis is fine, but if the method is generalised toInteger[]and the compared constant is outside the cached range (-128 to 127),==compares references and may fail even when the values match. Use.equals(Integer.valueOf(0))or unbox explicitly. - Counting the character
'0'on achar[]– the character'0'has numeric value48, soc == 0on achar[]counts null characters, not the digit zero. Compare against the character literal'0'explicitly for digit arrays. - Returning early on the first zero – a
returninside theifbody degenerates the method 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 (zero or non-zero)
- All zeros
- No zeros
- Zeros at the start, in the middle, and at the end
- Freshly allocated
new int[n](every element defaults to0, so count equalsn) Integer.MIN_VALUEandInteger.MAX_VALUEpresent (neither is0, so the count is unaffected)
Additional Considerations
The algorithm runs in O(n) time, since every element is visited exactly once, and there is no way to do better for an unordered array because any element can match. The space complexity is O(1), because only the counter and the loop variable are allocated regardless of the input size.
If the array is sorted in non-decreasing order, the problem collapses to two binary searches. The zeros occupy a contiguous range between the strict negatives on the left and the strict positives on the right. Finding the first index whose value is at least 0 and the first index whose value is strictly greater than 0 gives the count as the difference, in O(log n) total time.
On a double[] rather than an int[], there is one subtle floating-point question. The IEEE 754 standard defines two zeros, +0.0 and -0.0, with different bit patterns but a numeric equality that treats them as equal: -0.0 == 0.0 is true. For most counting purposes that is exactly the behaviour you want, but if you need to distinguish them, use Double.doubleToRawLongBits(value) == 0L to require the positive zero specifically.
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.
- How would you count zeros in a sorted array? – run two binary searches: one for the first index whose value is at least
0, one for the first index whose value is strictly greater than0; the count is the difference, which runs in O(log n) time. - How would you move all zeros to the end of the array while keeping the order of the non-zero elements? – two-pointer sweep: a write pointer collects non-zero values, a read pointer scans every value; after one O(n) pass, fill the tail with zeros.
- How would you count zeros in a 2D matrix sorted non-decreasingly in both rows and columns? – combine the staircase idea with the two-boundary technique: locate the row-wise zero band in O(log n) per row, or walk a staircase from a corner for a total of O(m + n).
- How would you count zeros in a stream of unknown length? – maintain a running count; the loop body is identical but termination comes from end-of-stream rather than array length.
- How would you count zeros in a very large array in parallel? – use
Arrays.stream(numbers).parallel().filter(v -> v == 0).count(), which splits the array into chunks, counts each chunk independently, and sums the chunk counts.
Conclusion
Counting the zero elements in an array in Java is a one-pass loop built around a single equality check, with two habits worth keeping in mind: validate against null but accept an empty array (whose count is a perfectly honest 0), and reread the condition to make sure the operator is == rather than =. Once those two habits are in place, the same shape of code generalises to sorted-input binary search, to the “move zeroes” variant, and to parallel reduce at scale.
Try adapting the code above to the move-zeroes variant: shift every non-zero element toward the front in order, then fill the rest of the array with zeros. The resulting array has every zero at the end and the non-zero elements in their original relative order.
You can learn more Array problems like this one here: Arrays.



