What is the output of the following Java program no. 8?

  1. class OverloadingCalculation3{
  2.   void sum(int a,long b){System.out.println(“a method invoked”);}
  3.   void sum(long a,int b){System.out.println(“b method invoked”);}
  4.   public static void main(String args[]){
  5.   OverloadingCalculation3 obj=new OverloadingCalculation3();
  6.   obj.sum(20,20);//now ambiguity  
  7.   }
  8. }

Output

OverloadingCalculation3.java:7: error: reference to sum is ambiguous
obj.sum(20,20);//now ambiguity  
     ^ 
      both method sum(int,long) in OverloadingCalculation3 
      and method sum(long,int) in OverloadingCalculation3 match
1 error

Explanation

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.