Design a class to overload a function compare() as follows:

Java Programming Language (Article) (Program)

24

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.

Program:

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);
        }
    }
}

Output:


                                        

Explanation:

Table of Variables

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:

Explanation:

  1. void compare(int a, int b)

    • Purpose: Compares two integer values and prints the greater one.
    • How It Works: Uses a simple if-else statement to determine which integer is larger and prints the result.
  2. void compare(char a, char b)

    • Purpose: Compares two characters based on their numeric (ASCII) values and prints the character with the higher value.
    • How It Works: Converts the characters to their ASCII values using (int) and compares them. The character with the higher value is printed.
  3. void compare(String a, String b)

    • Purpose: Compares the lengths of two strings and prints the longer one.
    • How It Works: Uses the 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.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.