ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

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

Correct answer: A. 1 hix

The return value is saved before finally runs. For f it is the int 1, so changing x later has no effect. For g it is a reference to the StringBuilder, and finally mutates that same object, so the caller sees hix.

More OOP with C++ and Java questions

Exams that ask this topic