Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Short method calling the integer method?

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?

like image 333
PSR Avatar asked Sep 14 '15 16:09

PSR


2 Answers

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.

like image 137
M A Avatar answered Nov 19 '22 07:11

M A


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

like image 5
Ben M. Avatar answered Nov 19 '22 07:11

Ben M.