There are ambiguities while using variable arguments in Java. This happens because two methods can definitely be valid enough to be called by data values. Due to this, the compiler doesn’t have the knowledge as to which method to call.
Example
public class Demo { static void my_fun(double ... my_Val){ System.out.print("fun(double ...): " + "Number of args: " + my_Val.length ); for(double x : my_Val) System.out.print(x + " "); System.out.println(); } static void my_fun(boolean ... my_Val){ System.out.print("fun(boolean ...) " + "The number of arguments: " + my_Val.length); for(boolean x : my_Val) System.out.print(x + " "); System.out.println(); } public static void main(String args[]){ my_fun(11.56, 34.78, 99.09, 56.66); System.out.println("Function 1 has been successfully called"); my_fun(true, false, true, false); System.out.println("Function 2 has been successfully called"); my_fun(); System.out.println("Function 3 has been successfully called"); } }
Output
Demo.java:23: error: reference to my_fun is ambiguous my_fun(); ^ both method my_fun(double...) in Demo and method my_fun(boolean...) in Demo match 1 error
A class named Demo defines a function named ‘my_fun’ that takes variable number of floating point values. The values are printed on the console using a ‘for’ loop. This function is overloaded and the parameters are boolean values that are varying in number. The output is displayed on the console using ‘for’ loop.
In the main function, the ‘my_fun’ is first called with floating ppoint values and then with Boolean values and then without any parameters. The exception that it results in, is displayed on the console.