ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
class R implements AutoCloseable {
String n;
R(String n, boolean fail) {
if (fail) throw new IllegalStateException(n);
this.n = n; System.out.print("open" + n + " ");
}
public void close() { System.out.print("close" + n + " "); }
}
// in main:
try (R a = new R("A", false); R b = new R("B", true)) {
System.out.print("body ");
} catch (IllegalStateException e) { System.out.print("caught" + e.getMessage()); }- A. openA caughtB
- B. openA closeA caughtB
- C. openA body closeA caughtB
- D. caughtB closeA
Correct answer: B. openA closeA caughtB
Resources are initialised in order; when creating b throws, the body is skipped but every resource ALREADY opened (a) is closed before the catch block runs.
More OOP with C++ and Java questions
- What happens when this is compiled? java interface I { int f(); } abstract class A { abstract long f(); } class C extends A implements I {…
- What happens when this is compiled? java interface I { default void f() { System.out.print("I"); } } abstract class A { public abstract…
- What is printed? java int[] arr = {1, 2, 3}; for (int x : arr) x = 2; System.out.print(Arrays.toString(arr));
- What is printed? java Set<String> s = new LinkedHashSet<>(List.of("a", "b", "c")); s.remove("a"); s.add("a"); s.add("b")…
- What is printed? java TreeMap<String, Integer> m = new TreeMap<>(); for (String k : new String[]{"9", "10", "100", "2"}) m.put(k…
- What is printed? java String r = Collections.max(List.of("pear", "fig", "banana", "kiwi"), Comparator.comparing(String::length))…