Java - What is the output: Autoboxing/Unboxing and Method Overloading, Object vs Long

Question

Consider the following two test() methods:

public void test(Long lObject) {
        System.out.println("Long=" + lObject);
}

public void test(Object obj) {
        System.out.println("Object=" + obj);
}

What will be printed when you execute the following code?

test(101);
test(new Integer(101));


Click to view the answer

Object=101
Object=101

Note

test(101) has to box int to an Integer, since there is no match for test(int), even after widening the int value.

test(101) becomes test(Integer.valueOf(101)). Then it cannot find any test(Integer) either.

Integer is a reference type and it inherits the Number class, which in turn inherits the Object class.

An Integer is an Object, and the test(Object obj) is called.

test(new Integer(101)) tries for test(Integer) method and cannot find it.

Then it finds test(Object) based on the subtype and supertype assignment rule for reference types.

Demo

public class Main {
  public static void main(String[] args) {
    test(101);/*from  ww  w  .j  av a 2s .c  o  m*/
    test(new Integer(101));

  }

  public static void test(Long lObject) {
    System.out.println("Long=" + lObject);
  }

  public static void test(Object obj) {
    System.out.println("Object=" + obj);
  }

}

Result

Related Quiz