Count Even Elements in an Array in Java
Problem
An even number is any integer exactly divisible by 2, with no remainder.
Given an array of integers, count how many of its elements are even.
Java Program
public class CountEven {
public static void main(String[] args) {
int[] arr = {4, 7, 10, 15, 22, 33, 8};
int count = 0;
for (int num : arr) {
if (num % 2 == 0) count++; // divisible by 2 with no remainder
}
System.out.println("Even elements: " + count);
}
}Output
Core Logic
A single pass through the array, checking each number's remainder when divided by 2, tallies every even value.
- 1A for-each loop visits each element of the array in turn.
- 2
num % 2 == 0checks whether the current number divides evenly by 2. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of even elements.
[4, 7, 10, 15, 22, 33, 8], the scan finds 4, 10, 22, and 8 — four even elements.Key Point: num % 2 also works correctly for negative even numbers in Java, since -4 % 2 evaluates to 0, not a negative remainder that would fail the check.
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 CountEvenStream {
public static void main(String[] args) {
int[] arr = {4, 7, 10, 15, 22, 33, 8};
// filter() keeps only even values; count() reduces to a single total
long count = Arrays.stream(arr).filter(num -> num % 2 == 0).count();
System.out.println("Even elements: " + count);
}
}
Output
Core Logic
The same divisibility check can filter a stream of the array's values down to just the even ones, then count what's left.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.filter(num -> num % 2 == 0)keeps only the values divisible by 2. - 3
.count()reduces the filtered stream down to a singlelongtotal.
[4, 7, 10, 15, 22, 33, 8] keeps 4, 10, 22, 8, so count() returns 4.Key Point: This is the same filter-then-count shape used throughout the string-counting programs on this site, just applied to an IntStream of numbers instead of characters.
Why: The stream still visits every element once, and count() reduces straight down to a single long without collecting anything.