Design a class to overload a method Number() as follows: (i) void Number(int num, int d) - To count and display the frequency of a digit in a number. Example: num = 2565685, d = 5 Frequency of digit 5 = 3 (ii) void Number(int n1) - To find and display the sum of even digits of a number. Example: n1 = 29865 Sum of even digits = 16 Write a main method to create an object and invoke the above methods.
Topic: Method overloading — digit frequency and even-digit sum
Answer
class NumberOverload { void Number(int num, int d) { int n = num, dig, f = 0;
while(n > 0) { dig = n % 10; if(dig == d) f++; n = n / 10; } System.out.println("Frequency of digit " + d + " = " + f); }
void Number(int n1) { int n = n1, dig, sum = 0;
while(n > 0) { dig = n % 10; if(dig % 2 == 0) sum = sum + dig; n = n / 10; } System.out.println("Sum of even digits = " + sum); }
public static void main(String args[]) { NumberOverload ob = new NumberOverload(); ob.Number(2565685, 5); ob.Number(29865); } }
Two methods with the same name, distinguished by the number of parameters — (int, int) against (int). That alone makes valid overloading.
Both use the same digit-extraction loop, which is the workhorse of this paper: dig = n % 10; takes the last digit ... test it ... n = n / 10; removes it by integer division running while n > 0.
The only difference is the test inside: dig == d for the frequency count, and dig % 2 == 0 for the even-digit sum.
Each method copies its argument into a working variable n, so the parameter itself is left intact for the printed message. Both are declared void, so they display rather than return — read the question, as returning the value instead would not match the specification.
Trace the examples: 2565685 has digits 5, 8, 6, 5, 6, 5, 2 — three fives. 29865 has even digits 6, 8 and 2, summing to 16. Both match.
num, n1 int - the numbers passed to the methods n int - working copy, reduced digit by digit dig int - the digit currently extracted d int - the digit whose frequency is to be counted f int - frequency counter sum int - running total of the even digits ob NumberOverload - object used to invoke the methods