ProgrammingVery hardProduct-company placement · Java

Which class compiles?

Which class compiles?
class K1 { static { throw new RuntimeException(); } }
class K2 { static { if (true) throw new RuntimeException(); } }
  1. A. Only K1
  2. B. Both
  3. C. Neither
  4. D. Only K2

Correct answer: D. Only K2

A static initializer must be able to complete normally; one that always throws is rejected by the compiler. Wrapping the throw in if (true) satisfies the flow analysis, and the exception then appears at run time as ExceptionInInitializerError.

More OOP with C++ and Java questions

Exams that ask this topic