Title: Count Positive Numbers in an Array
In this guide, you will learn how to count the positive numbers in an array using Java. The problem is a one-pass loop with a single comparison, and it is the cleanest place to pin down a definition that trips a lot of learners: zero is neither positive nor negative.
We will walk through the problem, build a complete program, trace it on a sample input, and then look at the > versus >= trap, the bitwise sign-bit lookalike, 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 positive. A number is positive when it is strictly greater than 0. For the input [4, -2, 0, 7, -1, 3, 8], the positive values are 4, 7, 3, and 8, so the answer is 4.
The whole problem hinges on one definition. In mathematics, “positive” means strictly greater than zero; “non-negative” means greater than or equal to zero. Writing value >= 0 instead of value > 0 counts non-negatives, which includes 0. If the problem asked for the count of non-negatives, that would be the right check, but it does 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 tracked.
- For each element
value, test whethervalue > 0. The strict comparison excludes0, which is neither positive nor negative. - Increment
countfor every matching element and return it once the loop ends.
Java Program
public class CountPositives {
public static int countPositives(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 = {4, -2, 0, 7, -1, 3, 8};
int positives = countPositives(values);
System.out.println("Positive count: " + positives);
}
}Explanation of the Program
The class CountPositives exposes a single static method, countPositives, 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 positives 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, and the choice of operator is deliberate. Writing value >= 0 would count 0, but 0 is neither positive nor negative. The strict > excludes 0 on the one hand and every negative value on the other, so only strictly positive values survive the comparison.
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 positives, negatives, and a 0, calls countPositives, and prints the result. Running it prints Positive count: 4, which correctly excludes the 0.
Step-by-Step Trace
Let us trace countPositives on the input [3, -5, 0, 8, -2, 6]. The expected final answer is 3, since the positive values are 3, 8, and 6.
| Iteration | value | value > 0? | count (before) | count (after) |
|---|---|---|---|---|
| 1 | 3 | yes | 0 | 1 |
| 2 | -5 | no | 1 | 1 |
| 3 | 0 | no | 1 | 1 |
| 4 | 8 | yes | 1 | 2 |
| 5 | -2 | no | 2 | 2 |
| 6 | 6 | yes | 2 | 3 |
At the end of iteration i, count holds the number of positive values among numbers[0..i-1]. Step 3 is the one that demonstrates the strict comparison: 0 fails the > 0 check and the counter stays put, exactly as the definition of “positive” requires.
Examples
Example 1: Mixed positive and negative values
A straightforward input where negatives and positives alternate. Only the strictly positive values are counted.
int[] nums = {5, -3, 2, -1, 7};
int positives = countPositives(nums);
System.out.println(positives);
// Positives: 5, 2, 7
// Output: 3Example 2: Negatives and a zero
No element is strictly greater than zero, so the count stays at 0. This example also pins down that 0 itself is excluded.
int[] nums = {-4, -2, 0, -1};
int positives = countPositives(nums);
System.out.println(positives);
// Output: 0Example 3: All positive values
Every element passes the strict comparison, so the count equals the array length.
int[] nums = {1, 2, 3, 4};
int positives = countPositives(nums);
System.out.println(positives);
// Output: 4Common Mistakes to Avoid
The algorithm looks like a one-liner, but the definition of “positive” and a tempting bitwise shortcut together produce several reliable traps. These are the mistakes learners actually make on this problem.
- Using
value >= 0– silently counts0as positive, which does not match the mathematical definition. For[0, 0, 0]the count comes out as3instead of0. Use the strictvalue > 0instead. - Using
!(value < 0)– the double-negative restatement ofvalue >= 0, so it has the same bug and is harder to read. Stick with the directvalue > 0. - Using
(value >>> 31) == 0– detects the sign bit, which is0for every non-negative value. This looks like a clever bitwise shortcut but still counts0as positive, so it has the same off-by-one asvalue >= 0. - Counting positive indices – writing
if (i > 0)inside an indexed loop counts every index except the first, which is almost always a bug. Test the element at the index, not the index itself. - Returning early on the first non-positive value – placing a
returninside anelsebranch exits the method as soon as any zero or negative 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 (positive, zero, or negative)
- All elements positive
- All elements negative
- All elements zero
- Mix of positive, negative, and zero values
Integer.MAX_VALUE(positive, counted) andInteger.MIN_VALUE(negative, excluded)
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 tip the count. 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 a binary search. The positives are a contiguous suffix of the array, so finding the smallest index k whose value is strictly greater than 0 gives a count of numbers.length - k in O(log n) time. The linear scan still runs in the same time or worse, so sort-aware callers should prefer the binary search.
A bitwise alternative worth knowing about is (value >>> 31) == 0, which checks the sign bit using an unsigned right shift. The expression evaluates to true for every non-negative value, which means it also includes 0. For counting positives it is the wrong tool, but it is the right tool for counting non-negatives, so it is useful to know what it actually tests.
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 positives, negatives, and zeros together in one pass? – keep three counters inside the same loop; the time stays O(n) and the space stays O(1).
- How would you count positives in a sorted array? – binary-search for the smallest index whose value is strictly greater than
0; the count isnumbers.length - index, which runs in O(log n) time. - How would you partition the array into negatives, zeros, and positives in-place? – use the Dutch National Flag algorithm with three pointers, which classifies every element in a single O(n) pass and O(1) extra space.
- How would you count positives 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 positives 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 positive numbers in an array in Java is a one-pass loop built around a single strict comparison, with two decisions tucked inside it: validate against null but accept an empty array (whose count is a perfectly honest 0), and use value > 0 rather than value >= 0 so 0 is correctly excluded. Once those two habits are in place, the same shape of code generalises to sorted-input binary search, Dutch-flag partitioning, streams, and parallel reduce at scale.
Try adapting the code above to return the three-way split (positives, zeros, negatives) rather than just the positive count. The whole method becomes a tiny sign-histogram over the array in a single pass.
You can learn more Array problems like this one here: Arrays.



