ProgrammingVery hardTCS NQT Digital · Accenture Advanced

What does this print?

What does this print?
static StringBuilder f() {
    StringBuilder sb = new StringBuilder("a");
    try { sb.append("b"); return sb; }
    finally { sb.append("c"); sb = new StringBuilder("z"); }
}
// main: System.out.print(f());
  1. A. ab
  2. B. z
  3. C. abc
  4. D. abcz

Correct answer: C. abc

The return value is the reference to the original builder, saved before finally; finally mutates that same object (adds c) but reassigning sb does not change the saved reference.

More OOP with C++ and Java questions

Exams that ask this topic