ProgrammingVery hardProduct company OA
A static method can be invoked through a reference variable that is null at run time without throwing NullPointerException. What is printed?
A static method can be invoked through a reference variable that is null at run time without throwing NullPointerException. What is printed?
class A {
static String tag() { return "static-A"; }
}
// in main:
A a = null;
System.out.println(a.tag());- A. It throws NullPointerException
- B. static-A
- C. null
- D. It throws a compile-time error
Correct answer: B. static-A
a.tag() is compiled to an invokestatic call resolved purely from the declared type A at compile time; the runtime value of a (even null) is never dereferenced, so no NPE occurs and "static-A" prints.
More OOP with C++ and Java questions
- What is printed? java class Counter { static int count = 0; Counter() { count++; } } // in main: Counter c1 = new Counter(); Counter c2 =…
- What is printed? cpp struct Base { void who() { cout << "Base"; } }; struct Derived : Base { void who() { cout << "Derived"; } }; int…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? cpp struct Animal { void speak() { cout << "..."; } }; struct Dog : Animal { void speak() { cout << "Woof"; } }; int…
- What is printed? (function-local static) cpp int next() { static int n = 0; return ++n; } int main() { cout << next() << next() << next()…
- What is printed? java class A { void greet() { System.out.print("A-inst "); } static void greet(int x) { System.out.print("A-static "); }…