Java ProgramsArraysCount Negative Elements in an Array

Count Negative Elements in an Array in Java

beginner·  Arrays  ·  Array

Problem

A negative number is any value strictly less than zero.

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

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

Java Program

Java
public class CountNegative { 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 less than zero } System.out.println("Negative elements: " + count); } }

Output

Negative elements: 3

Core Logic

A single pass through the array, checking each number against zero, tallies every negative value — the mirror image of counting positives.

How It Works
  1. 1A for-each loop visits each element of the array in turn.
  2. 2num &lt; 0 checks whether the current number is strictly less than zero.
  3. 3A match increments the count variable; anything else is skipped.
  4. 4After the loop, count holds the total number of negative elements.
For [5, -3, 8, -1, 0, 12, -7], the scan finds -3, -1, and -7 — three negative elements.
💡

Key Point: Zero is excluded from both the positive and negative counts — num &lt; 0 correctly treats it as neither, keeping the two counts from overlapping.

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 CountNegativeStream { public static void main(String[] args) { int[] arr = {5, -3, 8, -1, 0, 12, -7}; // filter() keeps only values strictly less than zero long count = Arrays.stream(arr).filter(num -> num < 0).count(); System.out.println("Negative elements: " + count); } }

Output

Negative elements: 3

Core Logic

The same comparison can filter a stream of the array's values down to just the negative ones, then count what's left.

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.filter(num -> num &lt; 0) keeps only the values strictly less than zero.
  3. 3.count() reduces the filtered stream down to a single long total.
Filtering [5, -3, 8, -1, 0, 12, -7] keeps -3, -1, -7, so count() returns 3.
💡

Key Point: Flipping &gt; 0 to &lt; 0 is the only change needed to turn the positive-counting stream into this one — the rest of the pipeline stays identical.

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