ProgrammingVery hardProduct-company placement · GATE CS

What is printed?

What is printed?
static int f() {
    int x = 1;
    try { return x; } finally { x = 2; }
}
static StringBuilder g() {
    StringBuilder sb = new StringBuilder("a");
    try { return sb; } finally { sb.append("b"); }
}
// in main:
System.out.print(f() + " " + g());
  1. A. 1 ab
  2. B. 2 ab
  3. C. 1 a
  4. D. 2 a

Correct answer: A. 1 ab

The return value is evaluated and saved before finally runs. For int that saved value is 1, so changing x does not matter; for g the saved value is a reference to the same StringBuilder, which finally then modifies.

More OOP with C++ and Java questions

Exams that ask this topic