Java Method Overloading for square calculation

Question

We would like to overload method square():

  • one that calculates the square of an int and returns an int
  • one that calculates the square of a double and returns a double.

Method calls cannot be distinguished only by return type.


// Overloaded method declarations.

public class Main 
{
   // test overloaded square methods
   public static void main(String[] args) 
   {//from  w  w w .java2 s. c  o m
      System.out.printf("Square of integer 7 is %d%n", square(7));
      System.out.printf("Square of double 7.5 is %f%n", square(7.5));
   }
   
   //your code here
}



// Overloaded method declarations.

public class Main 
{
   // test overloaded square methods
   public static void main(String[] args) 
   {
      System.out.printf("Square of integer 7 is %d%n", square(7));
      System.out.printf("Square of double 7.5 is %f%n", square(7.5));
   }
   
   // square method with int argument
   public static int square(int intValue)
   {
      System.out.printf("%nCalled square with int argument: %d%n", 
         intValue);
      return intValue * intValue;
   }

   // square method with double argument
   public static double square(double doubleValue)
   {
      System.out.printf("%nCalled square with double argument: %f%n",
         doubleValue);
      return doubleValue * doubleValue;
   }
}



PreviousNext

Related