Count Zeros in an Array in Java
Problem
Counting zeros means tallying every element in the array whose value is exactly 0.
Given an array of integers, count how many of its elements are zero.
Java Program
public class CountZeros {
public static void main(String[] args) {
int[] arr = {0, 5, 0, -3, 0, 8, 2};
int count = 0;
for (int num : arr) {
if (num == 0) count++; // exactly zero
}
System.out.println("Zeros: " + count);
}
}Output
Core Logic
A single pass through the array, checking each number for exact equality with zero, tallies every zero value.
- 1A for-each loop visits each element of the array in turn.
- 2
num == 0checks whether the current number is exactly zero. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of zero elements.
[0, 5, 0, -3, 0, 8, 2], the scan finds three zeros, at the first, third, and fifth positions.Key Point: This is a plain equality check, not a range check — it counts only values exactly equal to 0, neither the positive nor negative counting logic applies here.
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 CountZerosStream {
public static void main(String[] args) {
int[] arr = {0, 5, 0, -3, 0, 8, 2};
// filter() keeps only values equal to zero
long count = Arrays.stream(arr).filter(num -> num == 0).count();
System.out.println("Zeros: " + count);
}
}
Output
Core Logic
The same equality check can filter a stream of the array's values down to just the zeros, then count what's left.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.filter(num -> num == 0)keeps only the values equal to zero. - 3
.count()reduces the filtered stream down to a singlelongtotal.
[0, 5, 0, -3, 0, 8, 2] keeps the three zero values, so count() returns 3.Key Point: This is the same filter-then-count shape as counting positives or negatives, just with an equality check instead of an inequality.
Why: The stream still visits every element once, and count() reduces straight down to a single long without collecting anything.