Count Positive Elements in an Array in Java
Problem
A positive number is any value strictly greater than zero.
Given an array of integers, count how many of its elements are positive.
Java Program
public class CountPositive {
public static void main(String[] args) {
int[] arr = {5, -3, 8, -1, 0, 12, -7};
int count = 0;
for (int num : arr) {
if (num > 0) count++; // strictly greater than zero
}
System.out.println("Positive elements: " + count);
}
}Output
Core Logic
A single pass through the array, checking each number against zero, tallies every positive value.
- 1A for-each loop visits each element of the array in turn.
- 2
num > 0checks whether the current number is strictly greater than zero. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of positive elements.
[5, -3, 8, -1, 0, 12, -7], the scan finds 5, 8, and 12 — three positive elements.Key Point: Zero is neither positive nor negative — num > 0 correctly excludes it, unlike a looser check such as num >= 0.
Why: Each element is visited once, and only a single running counter is kept regardless of array size.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
public class CountPositiveStream {
public static void main(String[] args) {
int[] arr = {5, -3, 8, -1, 0, 12, -7};
// filter() keeps only values strictly greater than zero
long count = Arrays.stream(arr).filter(num -> num > 0).count();
System.out.println("Positive elements: " + count);
}
}
Output
Core Logic
The same comparison can filter a stream of the array's values down to just the positive ones, then count what's left.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.filter(num -> num > 0)keeps only the values strictly greater than zero. - 3
.count()reduces the filtered stream down to a singlelongtotal.
[5, -3, 8, -1, 0, 12, -7] keeps 5, 8, 12, so count() returns 3.Key Point: Zero is excluded here the same way it is in the loop version — filter(num -> num > 0) is a strict inequality, not >=.
Why: The stream still visits every element once, and count() reduces straight down to a single long without collecting anything.