Introduction

Finding the sum of even and odd numbers is one of the most common beginner programming exercises in Java because it combines two fundamental concepts: loops and conditional statements. While the logic itself is straightforward, this problem actually appears in two different forms that beginners often confuse.

Sometimes you're asked to calculate the sum of all even and odd numbers within a numeric range (such as 1 to 100). Other times, you're given an existing array of numbers and must separate the even and odd elements before calculating their sums. Although both versions rely on the same even/odd check, they solve different problems.

In this guide, you'll learn both approaches, along with a modern Java Streams solution and a mathematical shortcut that computes the sums for a range in constant time without using any loops.

Advertisement

Understanding the Problem

There are two common variations of this question.

Variation 1: Range-Based

Find the sum of all even numbers and all odd numbers between 1 and N.

Example:

1 to 10

Even numbers:
2 + 4 + 6 + 8 + 10 = 30

Odd numbers:
1 + 3 + 5 + 7 + 9 = 25

Variation 2: Array-Based

Given an array:

12 7 25 8 3 40 15

calculate:

  • Sum of all even elements

  • Sum of all odd elements

Unlike the first variation, the numbers are not necessarily sequential.


Method 1: Sum of Even and Odd Numbers Within a Range

This is the standard solution for numbers from 1 to N.

Java Program

public class SumEvenOddRange {

    public static void main(String[] args) {

        int n = 10;

        int evenSum = 0;
        int oddSum = 0;

        for (int i = 1; i <= n; i++) {

            if (i % 2 == 0) {
                evenSum += i;
            } else {
                oddSum += i;
            }
        }

        System.out.println("Sum of even numbers from 1 to " + n + ": " + evenSum);
        System.out.println("Sum of odd numbers from 1 to " + n + ": " + oddSum);
    }
}

Output

Sum of even numbers from 1 to 10: 30
Sum of odd numbers from 1 to 10: 25

Step-by-Step Trace (n = 10)

Number Even Sum Odd Sum
1 0 1
2 2 1
3 2 4
4 6 4
5 6 9
6 12 9
7 12 16
8 20 16
9 20 25
10 30 25

How It Works

The loop visits every number from 1 to n.

For every number:

  • If i % 2 == 0, it is added to evenSum.

  • Otherwise, it is added to oddSum.

After the loop finishes, both sums are printed.


Method 2: Sum of Even and Odd Numbers in an Array

This version works with an existing collection of numbers.

Java Program

public class SumEvenOddArray {

    public static void main(String[] args) {

        int[] numbers = {12, 7, 25, 8, 3, 40, 15};

        int evenSum = 0;
        int oddSum = 0;

        for (int num : numbers) {

            if (num % 2 == 0) {
                evenSum += num;
            } else {
                oddSum += num;
            }
        }

        System.out.println("Sum of even numbers in array: " + evenSum);
        System.out.println("Sum of odd numbers in array: " + oddSum);
    }
}

Output

Sum of even numbers in array: 60
Sum of odd numbers in array: 50

Verification

Even numbers:

12 + 8 + 40 = 60

Odd numbers:

7 + 25 + 3 + 15 = 50

Why Use the Enhanced For Loop?

The enhanced for loop

for (int num : numbers)

automatically visits every element in the array.

You don't need to manage an index variable, making the code cleaner and easier to read.


Method 3: Using Java Streams

Modern Java applications often use the Stream API.

Java Program

import java.util.Arrays;

public class SumEvenOddStreams {

    public static void main(String[] args) {

        int[] numbers = {12, 7, 25, 8, 3, 40, 15};

        int evenSum = Arrays.stream(numbers)
                            .filter(num -> num % 2 == 0)
                            .sum();

        int oddSum = Arrays.stream(numbers)
                           .filter(num -> num % 2 != 0)
                           .sum();

        System.out.println("Sum of even numbers: " + evenSum);
        System.out.println("Sum of odd numbers: " + oddSum);
    }
}

Output

Sum of even numbers: 60
Sum of odd numbers: 50

How Streams Work

The statement

Arrays.stream(numbers)

creates an IntStream.

The pipeline then performs:

  1. Convert the array into a stream.

  2. Filter only even (or odd) values.

  3. Add the remaining numbers.

Unlike loops, Streams focus on what should happen rather than how to perform each step.


Method 4: Mathematical Shortcut (No Loop Required)

For numbers from 1 to n, loops aren't actually necessary.

Well-known mathematical formulas can compute both sums instantly.

Java Program

public class SumEvenOddFormula {

    public static void main(String[] args) {

        int n = 10;

        int evenCount = n / 2;
        int evenSum = evenCount * (evenCount + 1);

        int oddCount = n - evenCount;
        int oddSum = oddCount * oddCount;

        System.out.println("Sum of even numbers from 1 to " + n + ": " + evenSum);
        System.out.println("Sum of odd numbers from 1 to " + n + ": " + oddSum);
    }
}

Output

Sum of even numbers from 1 to 10: 30
Sum of odd numbers from 1 to 10: 25

Why These Formulas Work

Suppose there are k even numbers.

The sequence is:

2, 4, 6, ..., 2k

Its sum equals:

k × (k + 1)

Similarly, the first k odd numbers are:

1, 3, 5, ..., (2k − 1)

Their sum is:

For n = 10:

Even count = 5
Even sum = 5 × 6 = 30

Odd count = 5
Odd sum = 5² = 25

This solution runs in constant time.


How Java Handles This Internally

Range-Based Loop

Variables such as:

  • n

  • i

  • evenSum

  • oddSum

are primitive int values stored on the stack.

No heap memory is allocated.


Array-Based Loop

The array

int[] numbers

is stored on the heap.

The enhanced for loop simply accesses each element one by one.


Java Streams

Arrays.stream() creates an internal stream pipeline.

Operations like:

filter()

are lazy, meaning they don't execute immediately.

The pipeline runs only when the terminal operation

sum()

is reached.


Formula-Based Method

Only a few primitive variables are used.

No loops or collections are required.

Memory usage remains constant.


Real-Life Analogy

Imagine sorting coins into two jars.

For every coin:

  • If its value is even, place it in the even jar.

  • Otherwise, place it in the odd jar.

At the end, add the values in each jar.

The program works exactly the same way—except instead of coins, it processes numbers.


Comparison Table

Method Works On Time Complexity Best Used When
Range Loop Numbers from 1 to n O(n) Standard interview solution
Array Loop Existing array O(n) Working with stored data
Java Streams Existing array O(n) Modern Java applications
Mathematical Formula Range 1 to n O(1) Performance-critical range calculations

Best Practices

  • Use the mathematical formula whenever the problem specifically asks for numbers from 1 to n.

  • Use loops when working with arrays or collections.

  • Prefer Streams when your project already follows a functional programming style.

  • Remember that negative numbers are still correctly classified as even or odd using the modulus operator.

  • Extract the summing logic into helper methods if it is reused throughout a larger application.


Common Mistakes

Confusing the Two Variations

The range-based formula only works for numbers from 1 to n.

It cannot be applied to an arbitrary array.


Forgetting to Reset the Sums

Always initialize:

int evenSum = 0;
int oddSum = 0;

before starting a new calculation.


Mixing Up the Formulas

Remember:

Even numbers:

k × (k + 1)

Odd numbers:


Assuming Streams Execute Immediately

Intermediate operations such as:

filter()

are lazy.

The stream is evaluated only when a terminal operation like:

sum()

is called.


Ignoring Negative Numbers

Negative values can also be even or odd.

For example:

-8 → even
-5 → odd

The modulus operator correctly classifies them.


Expert Tips

A strong interview answer is:

"If the problem is about numbers from 1 to n, I can either iterate through the range using a loop or use mathematical formulas. The sum of the first k even numbers is k × (k + 1), while the sum of the first k odd numbers is k², giving an O(1) solution. If the input is an array, I iterate through each element—or use Java Streams—to separate even and odd values before calculating their sums."

Clarifying whether the problem is range-based or array-based before writing code demonstrates careful problem analysis.


Pros and Cons

Method Advantages Disadvantages
Range Loop Simple and easy to understand O(n) time
Array Loop Works with any data Must examine every element
Java Streams Modern and concise Slight overhead for small arrays
Formula Method O(1) time Only works for sequential ranges

Frequently Asked Questions

How do I calculate the sum of even and odd numbers from 1 to n?

Loop from 1 to n and maintain two running totals, or use the mathematical formulas:

Even Sum = k × (k + 1)

Odd Sum = k²

where k is the number of even or odd numbers.


How do I calculate the sum of even and odd numbers in an array?

Iterate through the array.

If:

num % 2 == 0

add it to the even sum.

Otherwise, add it to the odd sum.


Can Java Streams be used?

Yes.

Arrays.stream(numbers)
      .filter(num -> num % 2 == 0)
      .sum();

calculates the sum of even numbers.

Changing the filter condition calculates the odd sum.


Do the mathematical formulas work for arrays?

No.

They only apply to continuous ranges such as:

1 to n

Do the formulas work with negative numbers?

No.

They assume a range starting at 1.

For ranges containing negative values, use a loop instead.


What is the time complexity of the loop solution?

O(n)

because every number is processed once.


What is the time complexity of the formula solution?

O(1)

because the result is computed directly using arithmetic.


How are negative numbers classified?

The modulus operator correctly identifies them.

Examples:

-6 → even
-9 → odd

Is this a common interview question?

Yes.

It is frequently asked to evaluate understanding of loops, conditionals, arrays, and Java Streams.


What is the difference between loops and Streams?

Loops are imperative, describing every step explicitly.

Streams are declarative, describing the desired result while the Stream API manages the iteration internally.


Can recursion be used?

Yes.

A recursive solution can process one number or one array element per call while accumulating separate even and odd sums.


Why does the even-number formula use k × (k + 1)?

Because the sum of the arithmetic sequence:

2, 4, 6, ..., 2k

simplifies mathematically to:

k × (k + 1)

which allows the result to be computed instantly without iteration.