Search code examples
javaunboxing

Why isn't unboxing applied in this java code?


public class P {
  String m(int i) {
    return "P.m(int)";
  }

  String m(Object o) {
    return "P.m(Object)";
  }
}

public class Test {
  public static void main(String[] args) {
    P p = new P();
    System.out.println(p.m(Integer.valueOf(42)));
  }
}

I can't understand why this program prints "P.m(Object)" instead of "P.m(int)".


Solution

  • Boxing and Unboxing conversions are only applied in the second stage of method overload resolution, and the second stage is only performed if the first stage doesn't find any matching candidate. In your example, String m(Object o) is found in the first stage, so the second stage is never performed.

    The reason boxing and unboxing are not used in the first stage is that auto-boxing and auto-unboxing conversions were introduced in a later version of Java, and the designers didn't want to break working code.