ProgrammingHardProduct-company placement · GATE CS

What happens?

What happens?
class T {
    static String s() { return "S"; }
    String i() { return "I"; }
}
// in main:
T t = null;
System.out.print(t.s());
System.out.print(t.i());
  1. A. S is printed, then a NullPointerException is thrown
  2. B. A NullPointerException is thrown before anything is printed
  3. C. It does not compile: a static method cannot be called through a variable
  4. D. SI is printed

Correct answer: A. S is printed, then a NullPointerException is thrown

A static method call through a variable uses only its static type; the reference is not dereferenced, so t.s() works even though t is null. The instance call t.i() needs the object and throws.

More OOP with C++ and Java questions

Exams that ask this topic