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();
    }
}
  1. A. abc
  2. B. abcxyz then an uncaught RuntimeException propagates after printing
  3. C. abcxyz with no exception at all
  4. 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

Exams that ask this topic