Java Method Overloading with automatic type conversions

Question

What is the output of the following code:

// Automatic type conversions apply to overloading.
public class Main {
  void test() {/*from  ww  w .  j  a v a  2 s . c om*/
    System.out.println("No parameters");
  }

  // Overload test for two integer parameters.
  void test(int a, int b) {
    System.out.println("a and b: " + a + " " + b);
  }

  // overload test for a double parameter and return type
  void test(double a) {
    System.out.println("Inside test(double) a: " + a);
  }
  public static void main(String args[]) {
    Main ob = new Main();
    int i = 88;

    ob.test(); 
    ob.test(10, 20);

    ob.test(i); // this will invoke test(double)
    ob.test(123.2); // this will invoke test(double)
  }
}


No parameters
a and b: 10 20
Inside test(double) a: 88.0
Inside test(double) a: 123.2

Note

When an overloaded method is called, Java will match the methods.

Java's automatic type conversions can happen in overload resolution.

The code does not define test(int).

Therefore, test(i) matches test(double).

If test(int) had been defined, it would have been called instead.

Java will employ its automatic type conversions only if no exact match is found.




PreviousNext

Related