public class OverLoad {
void method(Integer i){
System.out.println("Integer "+i);
}
void method(int i){
System.out.println("in "+i);
}
public static void main(String a[]){
OverLoad m= new OverLoad();
m.method(2); //it calls method(int i) why?
}
}
If i call the m.method(3)
it will call the int method why?
If i call the m.method((Integer)3)
then it will call the Integer method.
By default it going into primitive data type
By default it going into primitive data type
Well yes, because that's the exact type of the argument. The type of the literal 2
is int
, not Integer
(JLS 3.10.1). It's convertible to Integer
via a boxing conversion (JLS 5.1.7), but that will only happen if it's actually needed.
Overloading in Java occurs in three phases, as per JLS 15.12.2:
The first phase (ยง15.12.2.2) 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.
So m.method(2)
matches method(int)
in the first phase, so doesn't need to proceed to the second phase.
See more on this question at Stackoverflow