Title: Sum of Odd Elements in an Array
In this guide, you will learn how to find the sum of all odd elements in an array using Java. This is a classic warm-up problem that appears in beginner interviews and in the first week of a data structures course, because it combines two tiny skills that show up in almost every array question: walking the array once with a for loop, and filtering elements with a boolean condition.
We will build a full, compilable Java program, trace the algorithm step by step on a fresh input, work through three worked examples, and close with the common mistakes, edge cases, and interview follow-up questions that experienced interviewers like to ask on top of this problem.
Understanding the Problem
You are given an integer array numbers of length n. An element is called odd when its remainder on division by two is not zero, which in Java is written as numbers[i] % 2 != 0. Your task is to return the sum of every element that satisfies this condition.
The sum must handle negative odd numbers as well. In Java, the result of -3 % 2 is -1, not 1, so a check of the form x % 2 == 1 would silently miss every negative odd value. We will use x % 2 != 0 throughout to stay safe.
Approach and Algorithm Steps
The algorithm is a single linear pass with a running accumulator. There is no need to sort or allocate a second array, and no clever math shortcut because the odd and even positions are not predictable from the index alone, only from the value.
- Declare an integer accumulator
sumand initialize it to0. - Loop over the array from index
0tonumbers.length - 1. - For each element, test whether
numbers[i] % 2 != 0. - If the test passes, add
numbers[i]tosum. - If the test fails, do nothing and move on.
- After the loop finishes, return
sumas the final answer.
Java Program
Here is the complete, compilable Java program. The sumOfOdd method holds the logic and main drives it with a small test input so you can run the file directly with javac and java.
public class SumOfOddElements {
public static int sumOfOdd(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
return sum;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7};
int result = sumOfOdd(numbers);
System.out.println("Sum of odd elements: " + result);
}
}Explanation of the Program
The method sumOfOdd takes a single int[] and returns an int. It is static so it can be called from main without constructing an instance of SumOfOddElements.
Inside the method, sum starts at 0, which is the correct identity for addition. The for loop then visits every index from 0 up to but not including numbers.length. For each visit, the if guard tests the parity of numbers[i] and only runs the body when the value is odd.
The body is a single sum += numbers[i], which is shorthand for sum = sum + numbers[i]. When the loop exits, every odd element has contributed to sum exactly once, and the method returns it. The main method hands in a fixed test array and prints the result so the program is runnable end to end.
Step-by-Step Trace
Trace the algorithm on the input {4, 7, 2, 9, 6}. The expected final value of sum is 16, since the only odd elements are 7 and 9.
| Iteration | numbers[i] | numbers[i] % 2 != 0? | sum (before) | sum (after) |
|---|---|---|---|---|
| 1 | 4 | no | 0 | 0 |
| 2 | 7 | yes | 0 | 7 |
| 3 | 2 | no | 7 | 7 |
| 4 | 9 | yes | 7 | 16 |
| 5 | 6 | no | 16 | 16 |
At the end of iteration i, sum holds the total of every odd value in numbers[0..i-1]. That is the loop invariant, and after the final iteration it is exactly the value we want to return.
Examples
Example 1: All elements are odd
Every element passes the % 2 != 0 test, so sum accumulates all five values.
int[] input = {1, 3, 5, 7, 9};
int result = sumOfOdd(input);
// Output: Sum of odd elements: 25Example 2: No element is odd
Every element fails the parity test, so the if body never runs and sum remains 0. This is the correct answer for an array with no odd values.
int[] input = {2, 4, 6, 8, 10};
int result = sumOfOdd(input);
// Output: Sum of odd elements: 0Example 3: Mixed negative and positive values
The odd values are -3, -1, and 1, so the running total is -3 + -1 + 1 = -3. This example proves that the % 2 != 0 form catches negative odd numbers that % 2 == 1 would miss.
int[] input = {-3, -2, -1, 0, 1, 2};
int result = sumOfOdd(input);
// Output: Sum of odd elements: -3Common Mistakes to Avoid
These are the specific slips that cost learners points on this problem in interviews and homework reviews.
- Testing with
% 2 == 1– silently drops negative odd values because-3 % 2in Java is-1, not1. Usenumbers[i] % 2 != 0instead so both signs are detected. - Starting the loop at
i = 1– skips index0and omits its contribution. Start ati = 0since every element must be considered. - Using
intfor a huge accumulator – the running total can overflow silently when the odd values are nearInteger.MAX_VALUE. Changesumtolongwhen the inputs may be large. - Returning from inside the
ifbody – returningnumbers[i]on the first match returns only one element instead of the full sum. Returnsumonly after the loop exits. - Treating
0as odd – a straysum += 0is harmless numerically but shows a shaky mental model and will fail on variants that count odd elements. Remember that0 % 2is0, so zero is even.
Edge Cases to Test
Walk through this checklist before claiming the solution is done; interviewers watch for candidates who enumerate boundary inputs on their own.
- Empty array
- Single-element array holding an odd value
- Single-element array holding an even value
- All elements odd
- All elements even
- Mixed negative and positive odd values
Integer.MIN_VALUEorInteger.MAX_VALUEpresent- Null array reference
Additional Considerations
The time complexity is O(n) because the loop visits every element exactly once and each iteration does constant work. There is no way to beat O(n) in the worst case, since any unexamined element could flip the answer.
The space complexity is O(1). Only the sum accumulator and the loop counter i are allocated beyond the input, both of which are primitive int locals that live on the stack.
Overflow deserves a special mention. If the array has, say, one million copies of Integer.MAX_VALUE, the int accumulator will wrap around to a nonsensical negative value without any exception. For that regime, promote sum to long, or to BigInteger if even long is not wide enough.
Interview Follow-up Questions
Once the base solution is in, interviewers tend to probe depth with variants like these.
- What if the array is sorted? – the complexity stays
O(n)because odd and even values can interleave at any position, so sorting does not reveal the parity pattern. - What if the input arrives as a stream of unknown length? – maintain a running sum and add the current value only when it is odd; termination comes from end-of-stream rather than from
array.length. - What if the sum could exceed
Integer.MAX_VALUE? – widen the accumulator tolong, or toBigIntegerfor truly unbounded inputs. - What if the array has billions of elements and does not fit in memory? – partition the input, compute the sum of odd elements inside each partition independently, and add the partition sums; the partition step is embarrassingly parallel.
- What if you must do this with no mutable local variables? – use Java Streams:
Arrays.stream(numbers).filter(x -> x % 2 != 0).sum()expresses the same algorithm in a single expression.
Conclusion
Summing the odd elements of an array in Java is one loop, one if, and one accumulator. The algorithmic shape is trivial, but the problem is a surprisingly good teacher: it forces you to confront negative-number parity in Java, overflow in long-running sums, and the discipline of walking edge cases before you ship.
Try adapting the code to count odd elements, to find the maximum odd element, or to collect every odd element into a new array. Each variant reuses the same scaffold and makes the pattern second nature. You can learn more about similar problems in the Arrays category: https://dailyjavaconcept.com/category/arrays/.



