ProgrammingHardWipro · Cognizant pattern

What happens when this is compiled?

What happens when this is compiled?
class Picker {
    static void f(String s) { System.out.print("String"); }
    static void f(StringBuilder sb) { System.out.print("SB"); }
    public static void main(String[] a) { f(null); }
}
  1. A. Prints "String"
  2. B. Prints "SB"
  3. C. Compile-time error: reference to f is ambiguous
  4. D. NullPointerException at runtime

Correct answer: C. Compile-time error: reference to f is ambiguous

null is assignable to both String and StringBuilder, and neither parameter type is more specific than the other (they are unrelated types), so the compiler cannot pick one overload over the other and reports an ambiguous-call error.

More OOP with C++ and Java questions

Exams that ask this topic