AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardjavaexceptions

~90s

finally runs after the return value is fixed

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());
    }
}
Show the answer and the worked solution

Correct answer: D.

F1

Worked solution

  1. f evaluates its return expression, then runs the finally block before control leaves the method, so F is printed first.
  2. Only then does f hand 1 back to main.
  3. 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.

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.

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. 1
  2. 1F
  3. F
  4. F1
Show the answer and the worked solution

Correct answer: D. F1

Worked solution

  1. f evaluates its return expression, then runs the finally block before control leaves the method, so F is printed first.
  2. Only then does f hand 1 back to main.
  3. 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