ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
static class Resource implements AutoCloseable {
public void close() { System.out.print("closed "); }
}
public static void main(String[] args) {
try (Resource r = new Resource()) {
System.out.print("using ");
throw new RuntimeException("oops");
} catch (RuntimeException e) {
System.out.print("caught:" + e.getMessage() + " ");
}
}
}- A. using closed caught:oops
- B. using caught:oops closed
- C. closed using caught:oops
- D. using caught:oops
Correct answer: A. using closed caught:oops
The body prints "using ", then throws. Before that exception can be caught by the surrounding catch clause, the try-with-resources machinery closes every declared resource first, so "closed " prints next; only then does control reach the catch block, printing "caught:oops ".
More OOP with C++ and Java questions
- What happens when this is compiled? java class Base { void risky() throws java.io.IOException {} } class Sub extends Base { @Override void…
- What is printed? java public class Main { public static void main(String[] args) { Object o = "text"; try { Integer n = (Integer) o…
- What is printed? java public class Main { static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { return…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { Map<String, Integer> m = new…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abc"); try {…
- What is printed? java class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } B(int x) { this()…