Java generic method: Calculate sum of even and odd numbers
Java Generic: Exercise-2 with Solution
Write a Java program to create a generic method that takes a list of numbers and returns the sum of all the even and odd numbers.
Sample Solution:
Java Code:
// EvenOddSumCalculator.java
// EvenOddSumCalculator Class
import java.util.List;
public class EvenOddSumCalculator {
public static < T extends Number > void calculateNumberSum(List < T > numbers) {
double evenSum = 0;
double oddSum = 0;
for (T number: numbers) {
if (number.doubleValue() % 2 == 0) {
evenSum += number.doubleValue();
} else {
oddSum += number.doubleValue();
}
}
System.out.println("\nOriginal list of numbers: " + numbers);
System.out.println("Sum of even numbers: " + evenSum);
System.out.println("Sum of odd numbers: " + oddSum);
}
public static void main(String[] args) {
List < Integer > integers = List.of(1, 2, 3, 4, 5, 6, 7);
List < Double > doubles = List.of(2.0, 1.5, 4.5, 2.5, 1.5);
calculateNumberSum(integers);
calculateNumberSum(doubles);
}
}
Sample Output:
Original list of numbers: [1, 2, 3, 4, 5, 6, 7] Sum of even numbers: 12.0 Sum of odd numbers: 16.0 Original list of numbers: [2.0, 1.5, 4.5, 2.5, 1.5] Sum of even numbers: 2.0 Sum of odd numbers: 10.0
Explanation:
In the above exercise, we define a generic method calculateNumberSum() that takes a list of numbers as input. With the modulo operator %, the method iterates over the list and checks if each number is even or odd. If the number is even, it adds the value to the evenSum variable; otherwise, it adds the value to the oddSum variable.
Finally, the method prints out the sum of even and odd numbers.
In the main() method, we demonstrate the calculateNumberSum() method by passing two different lists: integers containing integers and doubles containing double values. For each list, the program calculates and prints the sum of even and odd numbers.
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Check equality of arrays.
Next: Find index of target element in list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/generic/java-generic-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics