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); }
}- A. Prints "String"
- B. Prints "SB"
- C. Compile-time error: reference to f is ambiguous
- 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
- What is printed? java class A { static void m() { System.out.println("A.static"); } } class B extends A { static void m() {…
- What happens when this is compiled? cpp struct A { virtual void f() final { cout << "A"; } }; struct B : A { void f() override { cout <<…
- What happens when this is compiled? java class A { int m() { return 1; } double m() { return 1.0; } }
- What is printed? cpp void f(int p) { cout << "nonconst "; } void f(const int p) { cout << "const "; } int main() { int x = 5; int p = &x…
- Does this compile? java class Outer { private int x = 5; class Inner { void show() { System.out.println(x); } } }
- What is printed? cpp struct Base { virtual void f() { cout << "Base"; } }; struct Derived : Base { void f() { cout << "Derived"; } }; int…