Count Negative Elements in an Array in Java
Problem
A negative number is any value strictly less than zero.
Given an array of integers, count how many of its elements are negative.
Java Program
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
Core Logic
A single pass through the array, checking each number against zero, tallies every negative value — the mirror image of counting positives.
- 1A for-each loop visits each element of the array in turn.
- 2
num < 0checks whether the current number is strictly less than zero. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of negative elements.
[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 < 0 correctly treats it as neither, keeping the two counts from overlapping.
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 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
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.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.filter(num -> num < 0)keeps only the values strictly less than zero. - 3
.count()reduces the filtered stream down to a singlelongtotal.
[5, -3, 8, -1, 0, 12, -7] keeps -3, -1, -7, so count() returns 3.Key Point: Flipping > 0 to < 0 is the only change needed to turn the positive-counting stream into this one — the rest of the pipeline stays identical.
Why: The stream still visits every element once, and count() reduces straight down to a single long without collecting anything.