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(); } }- A. Only K1
- B. Both
- C. Neither
- 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
- What happens? java class W { { if (true) throw new java.io.IOException("io"); } W() throws java.io.IOException { } }
- Which line fails to compile? cpp // C++17 struct S { int v; S(int x) : v(x) { } bool operator==(const S& o) const { return v == o.v; } }…
- What is printed? cpp struct B { void run() { step(); } virtual void step() { cout << "B"; } }; struct D : B { void step() override { cout…
- What is printed? cpp class A { int x = 3; friend int peek(const A& a) { return a.x; } }; int main() { A a; cout << peek(a); }
- Which function returns a reference that is SAFE to use after the call returns?
- Why does a C++ copy assignment operator conventionally return T& (that is, this)?