finally runs after the return value is fixed — Aptitude
finally runs after the return value is fixed: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 90 seconds
Question
What does this Java program print?
public class Main {
static int f() {
try {
return 1;
} finally {
System.out.print("F");
}
}
public static void main(String[] args) {
System.out.print(f());
}
}Options
- 1
- 1F
- F
- F1
Show the answer and the worked solution
Correct answer: D. F1
Worked solution
- f evaluates its return expression, then runs the finally block before control leaves the method, so F is printed first.
- Only then does f hand 1 back to main.
- main prints that 1 afterwards, so the output is F1.
Answer: F1.
The idea
A finally block is guaranteed to run on every exit path, including a return, and it runs before the caller resumes. The returned value is captured first, which is why the value itself is unaffected.
Shortcut. main can print f()'s result only after f has fully returned, and finally runs before that, so F appears before 1.
Common trap. 1 assumes return leaves the method at once and skips finally; a finally block runs on every exit path, return included.
All Programming Fundamentals questions · placement mock tests