ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
// static methods of the main class:
static void f(long x)    { System.out.print("long "); }
static void f(Integer x) { System.out.print("Integer "); }
static void f(Object x)  { System.out.print("Object "); }
static void f(int... x)  { System.out.print("varargs "); }
// in main:
f(3);
f('c');
f(3.0);
f(Integer.valueOf(3));
f();
  1. A. long long Object Integer varargs
  2. B. Integer long Object Integer varargs
  3. C. long long varargs Integer varargs
  4. D. long Integer Object Object varargs

Correct answer: A. long long Object Integer varargs

Java resolves overloads in phases: first without boxing or varargs, then with boxing, then with varargs. f(3): int widens to long in phase 1, so long beats Integer, which needs boxing. f('c'): char widens to long. f(3.0): double cannot narrow to long, so phase 1 finds nothing; phase 2 boxes to Double, which matches Object. f(Integer.valueOf(3)): both Integer and Object apply in phase 1 and Integer is more specific. f() matches only the varargs method.

More OOP with C++ and Java questions

Exams that ask this topic