How to Count Even and Odd Elements in an Array in Java
Counting even and odd numbers is often one of the first exercises Java learners encounter involving conditional logic inside a loop. Although the problem appears simple, it includes an important detail about negative numbers that even experienced developers sometimes overlook. This guide explains the standard approach, a bitwise alternative, and the negative-number nuance.
Problem Statement
Given an array like:
{10, 15, 22, 7, 8, 3}
Count:
- Even numbers:
10, 22, 8→ 3 - Odd numbers:
15, 7, 3→ 3
The Modulo Operator and Parity
A number's parity tells whether it is even or odd.
The standard way to check parity in Java is using the modulo (%) operator.
int number = 10;
if (number % 2 == 0) {
// Even
} else {
// Odd
}
When a number is divided by 2:
- Remainder
0→ Even - Non-zero remainder → Odd
Method 1: Classic Loop Using the % Operator
public class CountEvenOdd {
public static void main(String[] args) {
int[] numbers = {10, 15, 22, 7, 8, 3};
int evenCount = 0;
int oddCount = 0;
for (int num : numbers) {
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Even count: " + evenCount);
System.out.println("Odd count: " + oddCount);
}
}
This is the most common and recommended approach. It visits every element exactly once and counts even and odd numbers separately.
Method 2: Bitwise AND Trick
if ((num & 1) == 0) {
// Even
} else {
// Odd
}
The expression num & 1 checks only the least significant bit of the binary representation.
- Last bit
0→ Even - Last bit
1→ Odd
Although this can be slightly faster on some hardware, modern JVMs usually optimize % 2 equally well.
Method 3: Java Streams
import java.util.Arrays;
long evenCount = Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.count();
long oddCount = numbers.length - evenCount;
This approach uses Java Streams to count even numbers and calculates the odd count by subtracting from the total number of elements.
The Negative Number Gotcha
One subtle detail about Java's modulo operator is that it preserves the sign of the dividend.
For example:
System.out.println(-7 % 2);
Output:
-1
Notice that the remainder is -1, not 1.
Therefore, this check is incorrect:
if (num % 2 == 1) {
// Odd
}
It fails for negative odd numbers.
Instead, always use:
if (num % 2 == 0) {
// Even
} else {
// Odd
}
or
if (num % 2 != 0) {
// Odd
}
These approaches correctly handle both positive and negative numbers.
Step-by-Step Explanation
Traversing the Array
Each element is processed one at a time using a loop.
Checking Parity
If num % 2 == 0, the number is even.
Otherwise, it is odd.
Updating the Counters
The corresponding counter (evenCount or oddCount) is incremented.
After the loop finishes, both counters contain the required totals.
Internal Working (Memory View)
For the array:
numbers = [10, 15, 22, 7, 8, 3]
Processing:
10 % 2 = 0
Even count = 1
15 % 2 = 1
Odd count = 1
22 % 2 = 0
Even count = 2
7 % 2 = 1
Odd count = 2
8 % 2 = 0
Even count = 3
3 % 2 = 1
Odd count = 3
Final result:
Even count = 3
Odd count = 3
Real-Life Analogy
Imagine sorting numbered balls into two baskets.
For every ball:
- If its number is even, place it in the even basket.
- Otherwise, place it in the odd basket.
After processing every ball, simply count how many are in each basket.
Best Practices
- Always check
num % 2 == 0to identify even numbers. - For odd numbers, use
elseornum % 2 != 0instead ofnum % 2 == 1. - Use the enhanced
forloop when the array index is not required. - Use Java Streams for concise, functional-style code.
- Remember that zero is mathematically an even number.
Common Mistakes
- Checking
num % 2 == 1for odd numbers, which fails for negative odd values. - Forgetting that
0is an even number. - Misunderstanding how bitwise operations work with negative numbers.
- Using indexed loops unnecessarily when an enhanced
forloop is simpler.
Expert Tips
(num & 1) == 0correctly identifies even numbers for both positive and negative integers because Java uses two's complement representation.- This parity-checking logic is commonly reused for separating even and odd numbers, calculating separate sums, and partitioning arrays.
- Although Streams make the code concise, a simple loop is still slightly faster for performance-critical applications.
Comparison Table
| Method | Handles Negative Numbers Correctly? | Readability | Performance |
|---|---|---|---|
num % 2 == 0 |
✅ Yes | High | Excellent |
num % 2 == 1 |
❌ No | Medium | Excellent |
(num & 1) == 0 |
✅ Yes | Medium | Excellent |
Streams filter().count() |
✅ Yes | Very High | Good |
Frequently Asked Questions
Why shouldn't I use num % 2 == 1 to detect odd numbers?
Negative odd numbers produce a remainder of -1, not 1, causing this check to fail.
Is zero even or odd?
Zero is an even number because 0 % 2 == 0.
Does the bitwise AND trick work with negative numbers?
Yes. Java stores integers using two's complement representation, so (num & 1) correctly identifies even and odd numbers regardless of sign.
What is the safest way to check whether a number is odd?
Use:
num % 2 != 0
or simply use the else branch after checking for even numbers.
Can I count even and odd numbers using Java Streams?
Yes.
Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.count();
returns the number of even elements.
Is bitwise AND faster than the modulo operator?
In some low-level environments it can be slightly faster, but modern JVMs generally optimize both approaches very efficiently.
How can I count even and odd numbers in a 2D array?
Use nested loops to iterate through every row and every column while applying the same parity check to each element.
Can this logic be used for checking multiples of other numbers?
Yes. Replace 2 with another divisor, such as:
num % 3 == 0
to check for multiples of 3.