In Java, suppose we have a function with the parameter double a. Does it work if I pass an integer as argument? (I mean, is there an implicit conversion?) And i
Initially primitive widening will happen for a primitive type. For example you want to call
int input = 5; //int variable;
apply(input); //calling method with int value.
But your class not contains a method which argument accept int so compiler will go for primitive widening. It will check any apply method with java long argument present or not. If present that method will be invoked. If not it will check for apply with a float argument is present and then it will be selected. If that also not find it will look for apply with a double argument.
public void apply(long input) {
System.out.println("long"); // first pick by the compiler.
}
public void apply(float input) {
System.out.println("float"); // if above method not found this will be selected.
}
public void apply(double input) {
System.out.println("double"); // above two methods not present this will be selected.
}
Next, If all above three methods not found then compiler will look for Autoboxing this and try to convert that to its corresponding wrapper. for int its java.lang.Integer.So it will check for apply with Integer argument. If this found compiler will execute this method.
public void apply(Integer input) {
System.out.println("Integer");
}
Finally if none of the above present, compiler looks for any method with name apply which accepts int... or Integer... and the method is invoked.
public void apply(int... input) {
System.out.println("int...");
}
If your class contains only below two methods
public void apply(long input) {
System.out.println("long");
}
public void apply(float input) {
System.out.println("float");
}
and you want to pass a double value in to this method, it wont compile.
double input = 5d;
apply(input);
// The method apply(long) in the type YourClass
//is not applicable for the arguments (double
If you want to make that work you have to type cast that to something which can be accepted by your methods.
apply((int) input);
Then compiler will try to find a match by exact type or primitive widening or autoboxing or array matching way.