19
public class Yikes {
    public static void go(Long n) {
        System.out.print("Long ");
    }

    public static void go(Short n) {
        System.out.print("Short ");
    }

    public static void go(int n) {
        System.out.print("int ");
    }

    public static void main(String[] args) {
        short y = 6;
        long z = 7;
        go(y);
        go(z);
    }
}

This program is giving the output

int Long

I thought the output was

short Long

What is the reason for this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PSR
  • 39,804
  • 41
  • 111
  • 151

3 Answers3

16

The overload resolution section in the JLS explains why:

  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.

This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

  1. The second phase (§15.12.2.3) 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.

In the first phase, the compiler does not include the method go(Short n) in its resolution. Instead, it deems go(int n) to be an applicable method. This method is applicable because a short is widening converted to an int.

Community
  • 1
  • 1
M A
  • 71,713
  • 13
  • 134
  • 174
5

The compiler is preferring to convert a short into an int rather than box it into a Short object.

Ben M.
  • 2,370
  • 1
  • 15
  • 23
0

Try with this one:

Instead of

public static void go(Short n) {
    System.out.print("Short ");
}

try

public static void go(short n) {
    System.out.print("Short ");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prashant thakre
  • 5,061
  • 3
  • 26
  • 39