Java ProgramsArraysCount Even Elements in an Array

Count Even Elements in an Array in Java

beginner·  Arrays  ·  Array

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.

Input
[4, 7, 10, 15, 22, 33, 8]
Output
Even elements: 4

Java Program

Java
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

Even elements: 4

Core Logic

A single pass through the array, checking each number's remainder when divided by 2, tallies every even value.

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

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

modulo operatorfor-each loopcounter variable

Approach 2: Java 8

Java
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

Even elements: 4

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.

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

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