Method overload resolution in java

The compiler will consider not a downcast, but an unboxing conversion for overload resolution. Here, the Integer i will be unboxed to an int successfully. The String method isn’t considered because an Integer cannot be widened to a String. The only possible overload is the one that considers unboxing, so 8 is printed.

The reason that the first code’s output is 10 is that the compiler will consider a widening reference conversion (Integer to Object) over an unboxing conversion.

Section 15.12.2 of the JLS, when considering which methods are applicable, states:

  1. 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.

 

  1. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing […]

Leave a Comment