ProgrammingVery hardProduct company OA

What is printed?

What is printed?
public int test() {
    try {
        return 1;
    } finally {
        return 2;
    }
}
// caller prints test()
  1. A. 1
  2. B. 2
  3. C. Compilation error: duplicate return
  4. D. 1 then 2

Correct answer: B. 2

A return statement inside finally completely overrides (discards) any pending return from the try block — the finally block's return is the one that actually takes effect, so the method returns 2. This is widely considered bad practice precisely because it silently swallows the original return value (and would even swallow a pending exception).

More OOP with C++ and Java questions

Exams that ask this topic