Java - What is the output: Autoboxing/Unboxing and Method Overloading

Question

Suppose you have two methods in a class.

public void test(Integer iObject) {
        System.out.println("Integer=" + iObject);
}

public void test(int iValue) {
        System.out.println("int=" + iValue);
}

Suppose you make two calls to the test() method.

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


Click to view the answer

int=101
Integer=101

Note

For primitive parameter value, for example, test(10);

  • Try to find a method with the primitive type argument. If there is no exact match, try widening the primitive type to find a match.
  • If the previous step fails, box the primitive type and try to find a match.

For reference parameter value, test(new Integer(101));

  • Try to find a method with the reference type argument. If there is match, call that method. A match does not have to be exact. It should follow the subtype and super type assignment rule.
  • If the previous step fails, unbox the reference type to the corresponding primitive type and try to find an exact match, or widen the primitive type and find a match.

Demo

public class Main {
  public static void main(String[] args) {
    test(101);/*  w  w  w .j  a  va 2 s  .  com*/
    test(new Integer(101));

  }

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

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

Result

Related Quiz