SquareRoots

Updated Dani 2 Tallied Votes 208 Views Share

An example of method overloading. The program calls a function to get the square root of a number. The appropriate function (integer or double version) is executed.

package squareroots;
public class SquareRoots
{
    public static void main(String args[])
    {
        double x = 3, result = 0;
        int y = 5;
        result = getRoot(x);
        System.out.println("\n\tSquare root of " + x + " = " + result + "\n");
        System.out.println("\n\tSquare of result = " + result*result + "\n");
        result = getRoot(y);
        System.out.println("\n\tSquare root of " + y + " = " + result + "\n");
        System.out.println("\n\tSquare of result = " + result*result + "\n");
    }
    private static double getRoot(int inum)
    {
        System.out.println("\nIn the integer version");
        return Math.sqrt(inum);
    }
    private static double getRoot(double dnum)
    {
        System.out.println("\nIn the double version");
        return Math.sqrt(dnum);
    }
}