ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abc");
try {
modify(sb);
} finally {
System.out.print(sb);
}
}
static void modify(StringBuilder sb) {
sb.append("xyz");
throw new RuntimeException();
}
}- A. abc
- B. abcxyz then an uncaught RuntimeException propagates after printing
- C. abcxyz with no exception at all
- D. Compile-time error: cannot modify a parameter inside a method that throws
Correct answer: B. abcxyz then an uncaught RuntimeException propagates after printing
StringBuilder is mutable and passed by reference, so append("xyz") mutates the same object sb refers to in main, even though modify() then throws. finally still runs before the exception leaves main, printing the now-mutated "abcxyz"; since nothing catches the RuntimeException, it then terminates the program.
More OOP with C++ and Java questions
- What is printed? java class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } B(int x) { this()…
- What happens when this is compiled? java class A { A(int x) { System.out.print("A(int) "); } } class B extends A { B() {…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "~A"; } }; struct B { A a; B() { cout << "B"; } ~B() { cout << "~B"; }…
- What is printed? java class Base { protected int val; Base(int v) { val = v; System.out.print("Base(" + val + ") "); } } class Derived…
- What is printed? cpp struct Logger { Logger(string tag) : tag(tag) { cout << "open-" << tag << " "; } ~Logger() { cout << "close-" << tag…
- What is printed? java class A { A() { this(10); System.out.print("A() "); } A(int x) { System.out.print("A(int)=" + x + " "); } } public…