Java ProgramsArraysCount Zeros in an Array

Count Zeros in an Array in Java

beginner·  Arrays  ·  Array

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.

Input
[0, 5, 0, -3, 0, 8, 2]
Output
Zeros: 3

Java Program

Java
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

Zeros: 3

Core Logic

A single pass through the array, checking each number for exact equality with zero, tallies every zero value.

How It Works
  1. 1A for-each loop visits each element of the array in turn.
  2. 2num == 0 checks whether the current number is exactly zero.
  3. 3A match increments the count variable; anything else is skipped.
  4. 4After the loop, count holds the total number of zero elements.
For [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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each element is visited once, and only a single running counter is kept regardless of array size.

Key Concepts

comparison operatorfor-each loopcounter variable

Approach 2: Java 8

Java
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

Zeros: 3

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.

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.filter(num -> num == 0) keeps only the values equal to zero.
  3. 3.count() reduces the filtered stream down to a single long total.
Filtering [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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The stream still visits every element once, and count() reduces straight down to a single long without collecting anything.

Key Concepts

StreamIntStreamfilter()count()

Related Programs