Java ProgramsArraysCount Positive Elements in an Array

Count Positive Elements in an Array in Java

beginner·  Arrays  ·  Array

Problem

A positive number is any value strictly greater than zero.

Given an array of integers, count how many of its elements are positive.

Input
[5, -3, 8, -1, 0, 12, -7]
Output
Positive elements: 3

Java Program

Java
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

Positive elements: 3

Core Logic

A single pass through the array, checking each number against zero, tallies every positive 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 strictly greater than zero.
  3. 3A match increments the count variable; anything else is skipped.
  4. 4After the loop, count holds the total number of positive elements.
For [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.

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 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

Positive elements: 3

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.

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

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