ProgrammingHardProduct-company MCQ pattern

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 int g() {
    try { return 1; }
    finally { return 2; }
}
// in main:
System.out.print(f() + " " + g());
  1. A. 5 1
  2. B. 1 1
  3. C. 5 2
  4. D. 1 2

Correct answer: D. 1 2

In f, return x saves the value 1 before finally runs; changing x afterwards does not alter the saved int. In g, a return inside finally replaces the pending return 1, so g returns 2.

More OOP with C++ and Java questions

Exams that ask this topic