ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
// static methods of the main class:
static void f(Object o)  { System.out.print("Object"); }
static void f(String s)  { System.out.print("String"); }
static void f(Integer i) { System.out.print("Integer"); }
// in main:
f(null);
  1. A. Object
  2. B. Compile-time error: the call is ambiguous
  3. C. String
  4. D. A NullPointerException is thrown

Correct answer: B. Compile-time error: the call is ambiguous

null fits all three; the most specific method is chosen, but String and Integer are unrelated so neither is more specific than the other. With only f(Object) and f(String), String would win.

More OOP with C++ and Java questions

Exams that ask this topic