0

Following program prints Object as output, and when I remove the overloaded method contains Object as parameters, following compile time error is there:

The method m1(Long) in the type LangPackage is not applicable for the arguments (int)

 public class A {
    public static void main(String args[])
    {
      int x = 0;
       m1(x);

    }
    static void m1(Long l) {
            System.out.println("long");

        }

        static void m1(Object l) {
            System.out.println("Object");

        }
}

My query is why auto-boxing followed by widening is allowed for Objects not for Long type

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 1
    Implicit widening then autoboxing simply isn't defined to happen in the language spec. You are invoking the `Object` overload because it autoboxes to `Integer`. – Andy Turner Nov 19 '17 at 08:52

3 Answers3

6

auto-boxing boxes an int to an Integer.

An Integer is an Object, but it's not a Long. Therefore static void m1(Long l) cannot be chosen.

If you would call the method with a long parameter (i.e. if x would be a long), it would be auto-boxed to Long, and static void m1(Long l) would be preferred over static void m1(Object l).

Eran
  • 387,369
  • 54
  • 702
  • 768
1

If you call m1 with a long, the output is long:

m1(1L);

If you call with an integer - m1(1) - Java will choose the method with the Object parameter.

If you change input parameter from Long to long, the output is long for m1(1):

static void m1(long l) {

This works because int and long (not Integer and Long) are primitive types and Java converts from int to long in a case like this.

Integer does not extend Long, or vice versa. But both extend Number, so if you change to:

static void m1(Number n) {

That method will be called for m1(1)

Stefan
  • 2,395
  • 4
  • 15
  • 32
0

https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

IEE1394
  • 1,181
  • 13
  • 33