Design a class to overload a function compare() as follows:
(a) void compare(int, int) — to compare two integer values and print the greater of the two integers.
(b) void compare(char, char) — to compare the numeric value of two characters and print the character with the higher numeric value.
(c) void compare(String, String) — to compare the length of the two strings and print the longer of the two.
class Overload {
// Method to compare two integer values
void compare(int a, int b) {
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
}
// Method to compare the numeric values of two characters
void compare(char a, char b) {
if ((int) a > (int) b) {
System.out.println(a);
} else {
System.out.println(b);
}
}
// Method to compare the length of two strings
void compare(String a, String b) {
if (a.length() > b.length()) {
System.out.println(a);
} else {
System.out.println(b);
}
}
}
| Variable | Type | Description |
|---|---|---|
a |
int |
An integer value for comparison. |
b |
int |
Another integer value for comparison. |
a |
char |
A character for comparison based on numeric value. |
b |
char |
Another character for comparison based on numeric value. |
a |
String |
A string for comparison based on length. |
b |
String |
Another string for comparison based on length. |
This table summarizes the variables used in the compare() methods and their purposes.
Here's a concise explanation of each method in the Overload class:
void compare(int a, int b)
if-else statement to determine which integer is larger and prints the result.void compare(char a, char b)
(int) and compares them. The character with the higher value is printed.void compare(String a, String b)
length() method to get the length of each string and compares them. The string with the greater length is printed.These methods demonstrate function overloading by using the same method name compare() with different parameter types to perform various comparison operations.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.