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

Question

Suppose you have two test() methods.

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

public void test(long lValue) {
  System.out.println("long=" + lValue);
}

What will be printed if you execute the following code?

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


Click to view the answer

long=101
long=101

Note

test(101) widens 101 from int to long and executes the test(long) method.

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

A reference type is never widened. An Integer is never widened to Long.

Then, it unboxes the Integer to int and looks for test(int) method, and cannot find it either.

It widens the int and finds test(long) and executes it.

Demo

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

  }

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

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

}

Result

Related Quiz