Sum of Even Numbers with Varargs in Java
Create a Java program demonstrating a method with varargs that calculates the sum of even numbers
- The EvenSumCalculator class contains a static method named calculateEvenSum that takes a variable number of integers (int... numbers) as arguments.
- Inside the method, it prints the given numbers using Arrays.toString() to display the array contents.
- It initializes a variable sum to store the sum of even numbers and sets it initially to 0.
- It then iterates through each number in the numbers array.
- For each number, it checks if it's even by using the condition num % 2 == 0.
- If the number is even, it adds it to the sum.
- After iterating through all numbers, it returns the sum of even numbers.
- In the main method, the calculateEvenSum method is called with several integers as arguments.
- The sum of even numbers is then printed to the console.
Source Code
import java.util.Arrays;
public class EvenSumCalculator
{
static int calculateEvenSum(int... numbers)
{
System.out.println("Given Numbers : " + Arrays.toString(numbers));
int sum = 0;
for (int num : numbers)
{
if (num % 2 == 0)
{
sum += num;
}
}
return sum;
}
public static void main(String[] args)
{
int evenSum = calculateEvenSum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Sum of Even Numbers : " + evenSum);
}
}
Output
Given Numbers : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sum of Even Numbers : 30