Passing byte arguments to overloaded method

kbo :

I took this code snippet from some quiz, using IDE I executed it and get a result long, long but the correct answer is Byte, Byte, why I got different result? The question is related to JDK 11

public class Client {
    static void doCalc(byte... a) {
        System.out.print("byte...");
    }

    static void doCalc(long a, long b) {
        System.out.print("long, long");
    }

    static void doCalc(Byte s1, Byte s2) {
        System.out.print("Byte, Byte");
    }

    public static void main(String[] args) {
        byte b = 5;
        doCalc(b, b);
    }
}

EDITED:

The code was taken here: Oracle Certification Overview and Sample Questions (Page: 13, Question: 5)

Amit Bera :

So, if you go through the Java language specification for determining method signature at compile time it will be clear :

  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.

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

  3. The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

So, from the above steps, it is clear that in your case at first phase Java compiler will find a matching method which does doCalc(long a,long b). Your method doCalc(Byte s1, Byte s2) needs an autoboxing during the call so it will get less preference.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=304349&siteId=1