ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
String s = null;
switch (s) {
    case "a": System.out.print("A"); break;
    default:  System.out.print("D");
}
  1. A. D
  2. B. Nothing is printed
  3. C. A NullPointerException is thrown
  4. D. Compile-time error

Correct answer: C. A NullPointerException is thrown

A classic (non-pattern) switch on a String calls hashCode() on the value, so a null selector throws NullPointerException instead of falling to default.

More OOP with C++ and Java questions

Exams that ask this topic