ProgrammingHardHCL · Tech Mahindra pattern
A Java class's constructor runs `this.handle = acquire();` and then later throws an exception before returning. Which statement is correct?
- A. The finalize()/Cleaner mechanism is guaranteed to run immediately when the constructor throws
- B. try-with-resources on the caller's side will close handle even though the object reference was never assigned
- C. The object reference is never produced, so nothing outside the constructor can release handle automatically — the constructor itself must release it (e.g. in a catch block) or it leaks until an unreliable finalizer/cleaner eventually runs
- D. Java automatically calls a destructor on the partially built object to release handle
Correct answer: C. The object reference is never produced, so nothing outside the constructor can release handle automatically — the constructor itself must release it (e.g. in a catch block) or it leaks until an unreliable finalizer/cleaner eventually runs
Java has no destructors. If a constructor throws after acquiring a resource, the new object is discarded without ever being returned, so nothing automatically frees that resource — a leak unless the constructor itself catches the failure and releases the resource before rethrowing.
More OOP with C++ and Java questions
- What is printed? cpp struct N { int v; N(int x) : v(x) { std::cout << "N" << v << " "; } ~N() { std::cout << "~N" << v << " "; } }; int…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { public String toString() { return "B-" +…
- What is printed? java class Box<T> { T value; } // in main: Box<String> b1 = new Box<>(); Box<Integer> b2 = new Box<>()…
- What is printed (assume typical compiler codegen)? cpp struct Base { ~Base() { cout << "~Base "; } }; struct Derived : Base { int buf =…
- What happens when this line is compiled? java List<String>[] arr = new List<String>[10];
- What is printed? java class A { static void who() { System.out.print("A"); } } class B extends A { static void who() {…