1
class Demo {
    void methoda(Integer a) {
        SOP("integer");
    }
    void methoda(float a) {
        SOP("float");}
}

class test{
    P S V main(String[] args) { 
        Demo a=new Demo();
        a.methoda(3);
    }
}

Why is the output of this program "float" and not "Integer"?

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Why do you believe it should be the other way? Just your personal opinion, or did someone teach you wrong? – Andreas May 15 '19 at 18:08

1 Answers1

0

3 is of primitive type int and JVM first widens it to float instead of wrapping it into Integer

Widening in Java method overloading comes into picture when an overloaded method does not find its exact matching signature. In that case, when an exact match isn't found, the JVM uses the method with the smallest argument that is wider than the parameter.

Widening beats boxing because autoboxing feature was added to Java in J2SE 5.0 release. So, Java 5's designers decided that pre-existing code should not break and it should function the way it used to. Since widening capability already existed; therefore, an overloaded method gives preference to widening over boxing.

http://cs-fundamentals.com/java-programming/method-overloading-in-java.php

Ivan
  • 8,508
  • 2
  • 19
  • 30