Design a class to overload a function check() as follows: void check(String str, char ch) - to find and print the frequency of a character in a string. Example: str = "success", ch = 's' Output: number of s present is = 3 void check(String s1) - to display only the vowels from string s1, after converting it to lowercase. Example: s1 = "computer" Output: o u e
Topic: Method overloading — character frequency and vowels
Answer
class CheckOverload { void check(String str, char ch) { int f = 0; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == ch) f++; } System.out.println("number of " + ch + " present is = " + f); }
void check(String s1) { s1 = s1.toLowerCase(); char c; for(int i = 0; i < s1.length(); i++) { c = s1.charAt(i);
if(c == 'a' | | c == 'e' | | c == 'i' | | c == 'o' | | c == 'u')
System.out.print(c + " "); } System.out.println(); }
public static void main(String args[]) { CheckOverload ob = new CheckOverload(); ob.check("success", 's'); ob.check("computer"); } }
Two methods named check(), distinguished by their parameter lists — (String, char) and (String). That alone is valid overloading.
The first is a straightforward frequency count: walk the string with charAt(i) and increment a counter on each match. Note there is no break, because every occurrence must be counted, not just the first.
The second converts to lowercase FIRST, which halves the work — you then need only test against the five lowercase vowels rather than ten characters.
A neater alternative for the vowel test, worth mentioning: if("aeiou".indexOf(c) >= 0) — one condition instead of five, using the fact that indexOf returns -1 when the character is absent.
Trace the examples: "success" contains s at positions 0, 5 and 6, so the frequency is 3; "computer" yields o, u and e in that order. Both match the question.
str String - the string in which the character is counted ch char - the character whose frequency is required f int - frequency counter s1 String - the string whose vowels are to be displayed c char - holds each character of s1 in turn i int - loop variable ob CheckOverload - object used to invoke the methods