I am preparing for Java certification exam and one thing that I do not understand is below:
class Calculator {
public static long add(int a, long... b) {
System.out.println("int a, Var args long b");
int total = a;
for (long val : b) {
total += val;
}
return total;
}
public static long add(int a, Long b) {
System.out.println("int + Long");
return a + b;
}
}
public class OverloadTests {
public static void main(String[] args) {
var result = Calculator.add(1, 2);
System.out.println("result = " + result);
}
}
Java documentation (https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.2) says that:
1- The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase
2- The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
3- The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.
So, with these rules, I think this should happen:
Calculator.add(1, 2);
looks for (int, int)
signature, but fails to find. It also looks for (int, long)
, (int, float)
, and (int, double)
with this order. Since we are in step 1, we are not looking varargs, we shouldn't have a match.(int, Long)
, I expected the result to be "int + Long"
."int a, Var args long b"
.What am I missing in here? I was expecting the result to be "int + Long"
, but it is "int a, Var args long b"
EDIT: The code is taken from Udemy Course named Java SE 11 Developer 1Z0-819 OCP Course - Part 1
from the Author Tim Buchalka
If you remove the method add(int a, long... b)
you will find that your code won't compile because the remaining method add(int a, Long b)
cannot be called with add(1, 2)
because 2 is an int and a primitive int cannot be boxed into a Long. Likewise, the statement Long a = 2;
is invalid. Therefore the only matching candidate is add(int a, long... b)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With