While choosing the most appropriate method, compiler will first prefer to do Widening, then Boxing, and at the end, if all fails, Var-args. In your case, it will widen all the bytes
to ints
to get the matching method, with 3 int
type parameters.
For more details on this, see JLS §15.12.2.
Why is output int?
-
15-06-2023 - |
Pregunta
Why is the main method not calling the first method?
public class Test {
public static void printValue(byte...b) {
System.out.println("long");
}
public static void printValue(int i, int j, int k) {
System.out.println("int");
}
public static void main(String... args) {
byte b = 9;
printValue(b,b,b);
}
}
Why is the output int
?
Solución
Otros consejos
In other way, you have overloaded printValue
method. Now while making the call printValue(b,b,b);
compiler can't find a printValue
signature which takes byte
as argument type and have 3 arguments but it can find that printValue
has a overload which takes 3 parameter but accepts type int
and byte
can be implicitly casted to int
.
so it ends up calling the method overload printValue(int i, int j, int k)
while calling a method compiler first check the method name,parameter lists with datatype to match exactly, like method overloading.
if compiler doesn't get exact match for method, it looks for the best match. in your case it first check the method printValue() having three parameters.
it chooses public static void printValue(int i, int j, int k) method because -
-compiler doesn't get the exact matced method.
-it looks for appropriate match like byte->int , char -> int , int->long can be done explicitly.(widening) or autoboxing.** smaller data type can be converted into larger data type value. so it calls printValue(int i, int j, int k).** -your passed value can be easily converted into integer. 9- is also byte,char, integer data type value.