3

please help me explain this code behaviour:

public class Main {
      public static void var(Object... x) {
        System.out.println("Object");
    } 

    public static void var(Integer... x) {
        System.out.println("Integer...");
    }

    public static void main(String... args) {
        byte i = 0;
        Integer i2 = 127;
        var(i, i2);
    }
}

code above returns Object...

public class Main {
      public static void var(Object... x) {
        System.out.println("Object");
    } 

    public static void var(int... x) {
        System.out.println("int...");
    }

        public static void main(String... args) {
            byte i = 0;
            Integer i2 = 127;
            var(i, i2);
        }
    }

java: reference to var is ambiguous, both method var(java.lang.Object...) in inheritanceTest.Main and method var(int...) in inheritanceTest.Main match

I have these questions.

  1. Why each code variant Do returns corresponds value
  2. What principical differencies between these code snippets.

Really I cannot understand this part of jls a lot of time. My colleagues don't know it too.

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • 2
    http://www.coderanch.com/t/417622/java-programmer-SCJP/certification/Golden-Rules-widening-boxing-varargs – RKC Mar 23 '14 at 13:30
  • 1
    possible duplicate of [Why do two methods with signature (primitive, wrapper) and (primitive, primitive) cause the method call (wrapper, primitive) to be ambiguous?](http://stackoverflow.com/questions/20923888/why-do-two-methods-with-signature-primitive-wrapper-and-primitive-primitive) – Jeroen Vannevel Mar 23 '14 at 13:33
  • Also of note: [How java chooses between multiple applicable methods](http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.12.2.5) – Alan Mar 23 '14 at 13:34
  • http://geekexplains.blogspot.in/2009/06/choosing-most-specific-method-tricky.html – RKC Mar 23 '14 at 13:36

1 Answers1

2

In the first attempt with Object... and Integer...:

The reason the Integer... can't be matched is that java will not perform both an automatic widening cast and an auto-boxing in one operation. That means the byte can not be converted to an Integer by simply passing it to the method and hoping for byte --> int --> Integer. So the only match is to auto-box byte to Byte and match Object....

In the second attempt with Object... and int...:

Java can however perform an automatic widening cast from byte to int for the first parameter, and an auto-unboxing of Integer to int, so the int... matches. But it can also auto-box the byte to a Byte and leave the Integer, to match Object...

This is not matter of priorities. It is a matter of what java can do automatically in one step - it can either auto-box/unbox or automatically perform a widening cast.

Bohemian
  • 412,405
  • 93
  • 575
  • 722